与javascript的浮动总和 [英] Float sum with javascript
本文介绍了与javascript的浮动总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
JavaScript的数学是否被破坏?
我正在计算几个浮点值使用JavaScript和...我已经注意到一个从未见过的奇怪的事情。执行这段代码:
$ pre $ pa $ c>
我得到 4.699999999999999
我是否应该获得正确的价值? (假设这是不正确的...)
解决方案
一旦你阅读了每个计算机科学家应该知道什么是浮点运算 ,您可以使用 .toFixed()
函数:
var result = parseFloat('2.3')+ parseFloat('2.4');
alert(result.toFixed(2));
Possible Duplicate:
Is JavaScript's Math broken?
I'm calculating the sum of several float values using javascript and... I've noticed a strange thing never seen before. Executing this code:
parseFloat('2.3') + parseFloat('2.4')
I obtain 4.699999999999999
So... what sould I do to obtain a correct value? (supposed that this is incorrect...)
解决方案
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));
这篇关于与javascript的浮动总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文