Royi Namir Royi Namir - 3 months ago 12
Javascript Question

numbers and toFixed , toPrecision in Javascript?

Regarding the famous issue of

1.01+1.02
which is
2.0300000000000002


one of the workarounds is to use
toFixed
: e.g.

(1.01+1.02).toFixed(2) --->"2.03"


But I saw a solution with toPrecision

parseFloat((1.01+1.02).toPrecision(10))-->"2.03"


But lets have a look at
n
in


  • toFixed(n)

  • toPrecision(n)



How would I know what is n ?

0.xxxxxxxxxxx
+
0.yyyyyyyyyyyyy
---------------------
0.zzzzzzzzzzzzzzzzzzzzzzzzz
^
|
-----??????------


each number being added can have a different decimal digits...

for example :

1.0002+1.01+1.03333
--> 3.0435300000000005

how would I calculate the
n
here ? what is the best practice for this (specific) issue ?

Answer

This returns the expected output:

function add(){
    // Initialize output and "length" properties
    var length = 0;
    var output = 0;
    // Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);)
    for(var i = 0; i < arguments.length; i++){
        // If the current argument's length as string is longer than the previous one (or greater than 0 in case of the first argument))
        if(arguments[0].toString().length > length){
            // Set the current length to the argument's length (+1 is to account for the decimal point taking 1 character.)
            length = arguments[0].toString().length +1;
        }
        // Add the current character to the output with a precision specified by the longest argument.
        output = parseFloat((output+arguments[i]).toPrecision(length));
    }
    // Do whatever you with with the result, here. Usually, you'd 'return output;'
    console.log(output);
}
add();                     // Returns 0
add(1,2,3);                // Returns 6
add(1.01,2.01,3.03);       // Returns 6.05
add(1.01,2.0213,3.3333);   // Returns 6.3646
add(11.01,2.0213,31.3333); // Returns 44.3646

parseFloat even gets rid of trailing zero's for you.

This function accepts as many numbers as parameters as you wish, then adds these together taking the numbers' string length into account, when adding them. The precision used in the addition is dynamically modified to fit the "currently added" argument's length.

Fiddle