javascript - 数字小数问题

标签 javascript

我遇到了无法正确计算总数的问题。

我得到的总值为 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/

相关文章:

javascript - d3.js 和地理投影 albers/centers

javascript - Nodejs 将服务器 HTTP 更改为 HTTPS

jQuery 对话框内的 javascript setInterval() 在销毁或删除时不会停止

javascript - jQueryUI 自动完成错误 : this. 源不是函数

javascript - 在外部选项卡 url 应用程序中访问 Teams session 和其他信息

javascript - YUI 压缩器可以缩小 ASP.NET 内联脚本吗?

javascript - 如何禁用 Chrome 的 Ctrl + P

javascript - 联系表单7插件定制

javascript - 如何在 webpack 中使用 noParse?

javascript - Bacon.js 中的 mergeWith 与 onValues