首页 > 解决方案 > 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?

标签: javascript

解决方案


也许您可以使用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)) )


推荐阅读