Royi Namir - 1 year ago 117
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 ?

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);
}
`parseFloat` even gets rid of trailing zero's for you.