用javascript计算浮点数 [英] Float sum with javascript
本文介绍了用javascript计算浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
JavaScript 的数学有问题吗?
我正在使用 javascript 计算几个浮点值的总和......我注意到一个以前从未见过的奇怪事情.执行此代码:
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')
我得到4.699999999999999
那么...我该怎么做才能获得正确的值?(假设这是不正确的......)
So... what sould I do to obtain a correct value? (supposed that this is incorrect...)
推荐答案
一旦你读到了 每个计算机科学家都应该知道的关于浮点运算的知识你可以使用 .toFixed()
函数:
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屋!
查看全文