JavaScript 添加十进制数字问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10473994/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:30:03  来源:igfitidea点击:

JavaScript adding decimal numbers issue

javascriptnumbers

提问by u283863

So I am making a script that adds two numbers (decimal numbers) together, which I have encountered a problem.

所以我正在制作一个将两个数字(十进制数字)相加的脚本,我遇到了一个问题。

http://jsfiddle.net/DerekL/esqnC/

http://jsfiddle.net/DerekL/esqnC/

I made the script, it turns out pretty good:

我编写了脚本,结果非常好:

0.1 + 0.5  //0.6
0.2 + 0.3  //0.5

But soon I see:

但很快我就看到:

0.1 + 0.2  //0.30000000000000004
0.01 + 0.06  //0.06999999999999999

And it does not look right to me. I know it is a shortcoming of using float point with finite bits, but I can't find a way to fix that.

而且在我看来并不合适。我知道使用有限位的浮点数是一个缺点,但我找不到解决这个问题的方法。

Math.ceil   //No
Math.floor  //No
.slice      //No

UPDATE

更新

Is it possible to multiply the numbers by 1000 first, then add them then divide it by 1000?

是否可以先将数字乘以 1000,然后将它们相加然后除以 1000?

回答by Dagg Nabbit

Use toFixedto convert it to a string with some decimal places shaved off, and then convert it back to a number.

使用toFixed将其转换为与剃掉了一些小数位的字符串,然后将其转换回数字。

+(0.1 + 0.2).toFixed(12) // 0.3

It looks like IE's toFixedhas some weird behavior, so if you need to support IE something like this might be better:

看起来 IEtoFixed有一些奇怪的行为,所以如果你需要支持 IE,这样的东西可能会更好:

Math.round((0.1 + 0.2) * 1e12) / 1e12

回答by Community Driven Business

This is common issue with floating points.

这是浮点数的常见问题。

Use toFixedin combination with parseFloat.

使用toFixed与组合parseFloat

Here is examplein JavaScript:

这是JavaScript 中的示例

function roundNumber(number, decimals) {
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return parseFloat(newnumber); 
}

0.1 + 0.2;                    //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3

回答by Esteban Aliaga

Testing this Javascript:

测试这个 Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

结论

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

不要使用 Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

相反,使用 ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixedworks very well.

在 IE 9 中,toFixed效果很好。

回答by The Alpha

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

演示。