parseInt(123123123123123123123123); //return 1
parseInt(123123123123123123123123123); //return 1
parseInt(123123123123123123123123123123);//return 1
Test in chrome!
Definition and Usage The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes radix 16.
The main purpose of using the parseInt function is to extract a number from a string. This turns the returned value to an actual number. In the example above, 3 is a string and not an actual number.
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
Number() converts the type whereas parseInt parses the value of input. As you see, parseInt will parse up to the first non-digit character. On the other hand, Number will try to convert the entire string.
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.
A little creative reading of the documentation for parseInt()
provides an answer for this. Here's what's happening:
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")
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With