Royi Namir Royi Namir - 1 year ago 117
Javascript Question

numbers and toFixed , toPrecision in Javascript?

Regarding the famous issue of

which is

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

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

But I saw a solution with toPrecision


But lets have a look at

  • toFixed(n)

  • toPrecision(n)

How would I know what is n ?


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

for example :

--> 3.0435300000000005

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

Answer Source

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;'
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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download