Odd behavior with ParseFloat when my string is too long

426 Views Asked by At

I was making a calculator (something like excel in javascript) and I have found a strange behavior with ParseFloat.

parseFloat(999999999999999)  //999999999999999

parseFloat(9999999999999999) //10000000000000000

parseFloat(9999999999999899) //9999999999999900

Is there a limit with parseFloat function in javascript? Following ECMA Standard there is no issue about this.

1

There are 1 best solutions below

0
On

Float is not an endless container. Consider this example:

console.log(0.1 + 0.2 == 0.3) // Prints... FALSE!

Or, another case:

console.log(99999999999999999999999999999999999) // Prints 1e+35

...while 1e+35 is just 1 with 35 zeroes. Original number (9999...) is so large and precise that JS starts cutting lower digits to store at least something - the source is too big to save in float.

This actually happens because of internal float conversions made by JavaScript engine and the philosophy of float type is that higher digits are more important that lower.

Your case is somewhat similar. This is because floating point type accuracy depends on its value length. So, If your value is too big or too small, you will lose precision for lower digits.

Thus you should never trust float and never compare it with other values using '==' of '===' - it may be anything.