是否保留小数点后两位可以解决精度损失



经典的精度损失案例

0.3 - 0.1  // 0.19999999999999998

但是,如果我们只计算小数点后两位的数字,并使用toFixed(2)这有风险吗?

(0.3 - 0.1).toFixed(2)  // '0.20'

最终可能会得到奇怪的舍入行为。也许不要用它来赚钱

console.log((0.3 - 0.005).toFixed(2))//should be .29
console.log(Math.round((0.3 - 0.005)*100)/100)//should be .3(0)

可以用big.js解决,只有24.4kb

最新更新