javascript - How can I simplify this code to get a correct decimal place for a number?
问题描述
Here's the code below:
let moneyToReturn = 0.5
let note = 0.01
let sum = 0
while(moneyToReturn-note>=0){
moneyToReturn = ((moneyToReturn*10 - note*10)/10).toFixed(2)
sum = ((sum*10 + note*10)/10).toFixed(2)
// moneyToReturn -= note
// sum += note
console.log(sum)
}
To make sure that I'm not logging my sum with crazy decimal places on each computation I need to write this code.
((x * 10 + y * 10)/10).toFixed(2)
What is the better/shorter way of doing that?
解决方案
也许您可以使用parseFloat
来避免像这样的算术需求?
while(moneyToReturn-note>=0){
moneyToReturn = parseFloat((moneyToReturn - note).toFixed(2))
sum = parseFloat((sum + note).toFixed(2))
// moneyToReturn -= note
// sum += note
console.log(sum)
}
您应该会发现,parseFloat
如上所示的使用在功能上等同于((x * 10 + y * 10)/10).toFixed(2)
以下代码示例所示:
var x = 0.1
var y = 0.3
console.log('Current method', ((x * 10 + y * 10)/10).toFixed(2) )
console.log('Concise method', (parseFloat(x + y).toFixed(2)) )
推荐阅读
- php - 使用 laravel 进行客户端身份验证和用户身份验证
- javascript - Nuxt 生成,状态 500
- python - 我从网站上抓取了一个视频并下载了它,但视频无法播放
- r - 警告:“在文档对象'FANG'中使用但不在代码中的变量:”
- python - 如何根据另一个数据帧过滤多索引数据帧
- jquery - 如何在按钮单击时显示和隐藏部分视图?
- yql - 批量检查 Vespa 中的文档是否存在
- salesforce - 根据行项目创建 8000 多个 pdf
- python - 将继承的 mixin 方法装饰为 pyqtSlot
- javascript - 从 C++ Node.js 插件调用现有 JavaScript 函数 - 从另一个线程