JavaScript adding decimal numbers issue

JavascriptNumbers

Javascript Problem Overview


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

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?

Javascript Solutions


Solution 1 - Javascript

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

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

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

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

Solution 2 - Javascript

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

DEMO.

Solution 3 - Javascript

This is common issue with floating points.

Use toFixed in combination with parseFloat.

Here is example in 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

Solution 4 - Javascript

Testing this 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

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

In IE 9, toFixed works very well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDerek 朕會功夫View Question on Stackoverflow
Solution 1 - JavascriptDagg NabbitView Answer on Stackoverflow
Solution 2 - JavascriptThe AlphaView Answer on Stackoverflow
Solution 3 - JavascriptCommunity Driven BusinessView Answer on Stackoverflow
Solution 4 - JavascriptEsteban AliagaView Answer on Stackoverflow