在 javascript 中使用 toFixed(2) 会产生不良结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16064330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using toFixed(2) in javascript is producing undesirred results
提问by Damien
I'm doing this:
我这样做:
var refundAmount = parseFloat($('#refundAmount2').val().replace('$',''));
var refundReceived = $('#refundReceived');
var remainderAmount = refundAmount-parseFloat(refundReceived.val().replace('$',''));
alert(parseInt(remainderAmount).toFixed(2));
no matter what i do, the result always ends with 2 decimal places being '.00'. So if the first number is 200.12 and the second is 100.08, it should be alerting me with 100.04 but instead i get 100.00. Any ideas as to why this is happening? Thanks all!
无论我做什么,结果总是以 2 个小数位为 '.00' 结束。因此,如果第一个数字是 200.12,第二个数字是 100.08,它应该用 100.04 提醒我,但我得到的是 100.00。关于为什么会发生这种情况的任何想法?谢谢大家!
回答by Antony
You used parseInt
to convert that number to an integer and then used toFixed(2)
to convert it to a number with 2 decimal places. Adding 2 decimal places to an integer will always result in .00
.
您曾经parseInt
将该数字转换为整数,然后toFixed(2)
将其转换为带有 2 个小数位的数字。将 2 个小数位添加到整数将始终导致.00
.
Try
尝试
alert(remainderAmount.toFixed(2));
See DEMO.
见演示。
回答by djs
You're getting it as an int with parseInt(), then doing the toFixed(). So you're putting decimal places on an int.
您使用 parseInt() 将其作为 int 获取,然后执行 toFixed()。所以你把小数位放在 int 上。