使用 javascript 浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12511057/
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
Float sum with javascript
提问by davioooh
Possible Duplicate:
Is JavaScript's Math broken?
可能的重复:
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:
我正在使用 javascript 计算几个浮点值的总和……我注意到了一件以前从未见过的奇怪事情。执行这段代码:
parseFloat('2.3') + parseFloat('2.4')
I obtain 4.699999999999999
我得到4.699999999999999
So... what sould I do to obtain a correct value? (supposed that this is incorrect...)
那么......我该怎么做才能获得正确的价值?(假设这是不正确的......)
回答by Darin Dimitrov
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmeticyou could use the .toFixed()
function:
一旦你阅读了What Every Computer Scientist should Know About Floating-Point Arithmetic,你就可以使用这个.toFixed()
函数:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?
回答by Gyan Chandra Srivastava
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
我想它会给你解决方案