我遇到了无法正确计算总数的问题。
我得到的总值为 24
,我期望 25.60000
我做错了什么?
例子:
var a = "12.80000"; //Set as string deliberately
var b = "12.80000";
var total = 0;
total += roundAmount(parseInt(a), 5);
total += roundAmount(parseInt(b), 5);
console.log(total);
function roundAmount(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
最佳答案
你正在用 parseInt 去掉小数点,你需要 parseFloat。
var a = "12.80000"; //Set as string deliberately
var b = "12.80000";
var total = 0;
total += roundAmount(parseFloat(a), 5);
total += roundAmount(parseFloat(b), 5);
console.log(total);
function roundAmount(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
你不会在输出中得到额外的尾随零,如果你想要它们,你需要在输出时使用 toFixed(5) 。
关于javascript - 数字小数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376113/