Why parsing a very large number to integer return 1

parseInt(123123123123123123123123); //return 1 parseInt(123123123123123123123123123); //return 1 parseInt(123123123123123123123123123123);//return 1 

Test in chrome!

+5
source share
2 answers

A little creative reading of the documentation for parseInt() gives an answer to this question. Here's what happens:

  • parseInt expects a string to be its first argument. If it is not, it will convert it to a string. This is actually fun because it seems to be happening by ... wrapping it in quotation marks and passing it through .toString() , which in this case is more or less the opposite of parseInt() . In your example, parseInt(123123123123123123123123); becomes parseInt("1.2312312312312312e+29") .

  • Then it takes the value converted to a string and passes it through parseInt() . As the documentation shows, if he encounters a non-numeric character, he interrupts and proceeds with what he still has ... and he truncates the integer. So he takes "1.231231231231231212e + 29", reaching +, interrupting, smoothing out "1.2312312312312312" instead and coming up with 1.

Unintended consequences!

You will see this problem only if the ints are large enough so that when converted to strings, they appear in exponential notation. The main problem is that even if you think that parseInt() and Number.toString() will mirror each other ... they are not, because int values ​​passed through toString() can generate strings that parseInt() not understood.

+6
source

First, always specify a radius (second parameter) to avoid fortune telling.

Secondly, parseInt expects a string, so add quotes around your number.

 parseInt("123123123123123123123123123123", 10) 1.2312312312312312e+29 

Mozilla Developer Link Good documentation on this feature and examples. As for the grounds, they say:

Always specify this option to eliminate reader confusion and ensure predictable behavior. Different implementations lead to different results when rexix is ​​not specified.

+2
source

All Articles