【问题标题】:Using toFixed(2) in JavaScript is producing undesired results在 JavaScript 中使用 toFixed(2) 会产生不希望的结果
【发布时间】:2013-04-17 15:36:59
【问题描述】:

我正在这样做:

var refundAmount = parseFloat($('#refundAmount2').val().replace('$',''));
var refundReceived = $('#refundReceived');
var remainderAmount = refundAmount-parseFloat(refundReceived.val().replace('$',''));

alert(parseInt(remainderAmount).toFixed(2));

无论我做什么,结果总是以小数点后 2 位为 '.00' 结尾。所以如果第一个数字是 200.12,第二个是 100.08,它应该用 100.04 提醒我,但我得到的是 100.00。

为什么会发生这种情况?

【问题讨论】:

  • parseInt(remainderAmount) 将数字转换为整数,然后toFixed(2).00 附加到它。这可能是不受欢迎的,但这是可以预见的结果。我想你想要alert(parseFloat(remainderAmount.toFixed(2)));

标签: javascript parsefloat tofixed


【解决方案1】:

您使用parseInt 将该数字转换为整数,然后使用toFixed(2) 将其转换为具有2 个小数位的数字。向整数添加 2 位小数将始终导致 .00

试试

alert(remainderAmount.toFixed(2));

DEMO

【讨论】:

  • 这里不需要 parseFloat,因为剩余量已经是一个数字了。
【解决方案2】:

你通过 parseInt() 将它作为一个 int 得到,然后执行 toFixed()。所以你把小数位放在一个 int 上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2021-08-15
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    相关资源
    最近更新 更多