刘晚林
刘晚林

Reputation: 65

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!

Upvotes: 5

Views: 631

Answers (2)

S McCrohan
S McCrohan

Reputation: 6693

A little creative reading of the documentation for parseInt() provides an answer for this. Here's what's happening:

  1. parseInt expects its first argument to be a string. If it isn't, it converts it to a string. This is actually hilarious, because it appears to do that by...wrapping it in quotes and passing it through .toString(), which is more or less the converse of parseInt() in this case. In your example, parseInt(123123123123123123123123); becomes parseInt("1.2312312312312312e+29").

  2. THEN it takes the converted-to-string value and passes it through parseInt(). As the documentation tells us, if it encounters a non-numeric character, it aborts and goes with what it has so far...and it truncates to an integer. So it's taking "1.2312312312312312e+29", reaching the +, aborting, parsing "1.2312312312312312" instead, and coming up with 1.

Unintended consequences!

You'll only see this problem with ints large enough that when converted to strings, they render in exponential notation. The underlying problem is that even though you'd think parseInt() and Number.toString() would mirror each other...they don't, quite, because int values passed through toString() can generate strings that parseInt() doesn't understand.

Upvotes: 6

MaxVT
MaxVT

Reputation: 13234

First, always specify the radix (second parameter) to avoid guessing.

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

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

Mozilla developer reference has good documentation of this function and examples. Regarding the radix, they say:

Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

Upvotes: 2

Related Questions