gpt4 book ai didi

javascript - 数字小数问题

转载 作者:行者123 更新时间:2023-11-30 14:36:22 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com