'Why does JavaScript's parseInt(0.0000005) print "5"?

I've read an article about JavaScript parseInt, which had this question:

parseInt(0.5);      // => 0
parseInt(0.05);     // => 0
parseInt(0.005);    // => 0
parseInt(0.0005);   // => 0
parseInt(0.00005);  // => 0
parseInt(0.000005); // => 0

parseInt(0.0000005); // => 5

Why is this happening?



Solution 1:[1]

(This is more of a long comment rather than a competing answer.)

The unwanted conversion leading to this weird effect only happens when passing the value to parseInt as a number type - in this case it appears that the compiler (or interpreter or whatever drives JS) auto-converts the number into a string for you, as the string type is the expected type of the function parameter

That number-to-string conversion function, unfortunately, prefers the engineering number format when it would get too long otherwise.

Also, the conversion may lead to loss of precision, which is something every programmer has to be aware of whenever dealing with decimal (non-integer) numbers.

If you instead remember to place the to-be-parsed value into a string yourself, then you'll not get such unexpected results:

let n = '0.0000005';
console.log(parseInt(n))

Will print 0 as desired.

Lessons learned:

  • Avoid implicit type conversion wherever you can.
  • Avoid parseInt and similar functions that do not let you know if the string to be parsed has extra non-fitting data. E.g, int-parsing "x" or "1x" should both tell you that this is not a proper int number. In this regard, parseInt exhibits bad behavior by ignoring extra data in the string and not telling us. A good parser function either tells you where it stopped (so that you can check if there's garbage left over) or fails when it finds unexpected data.

Solution 2:[2]

Please respect the data type!

In Chrome console:

parseInt("0.5");
0
parseInt("0.05");
0
parseInt("0.005");
0
parseInt("0.0005");
0
parseInt("0.00005");
0
parseInt("0.000005");
0
parseInt("0.0000005");
0
parseInt("0.00000005");
0
parseInt("0.000000005");
0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 OleksandrZiborov