Is parseInt() supposed to work like this?

Yes: parseInt() is absolutely meant to work like that; to quote the Mozilla Developer Network entry:

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

It seems that parseInt() is explicitly expecting to take a string and will take the first sequence of numbers (until it encounters an invalid numerical character) and return that as a number of whatever base was specified in the radix parameter.

Incidentally, to reduce errors when parsing the strings passed to parseInt() remember to use the radix parameter, for example:

parseInt('123odod24',10); // for base-10
parseInt('123odod24',16); // for base-16

Reference:

  • parseInt() at the MDC.

Yes, cf all the anwers. I'd like to add that this is why checking if certain value can be converted to a number, it's better to use Number or just +.

Number("123blahblahblah456"); //=> NaN
Number("123"); //=> 123
+"97.221" //=> 97.221
// if the conversion result needs to be an int
Math.round(Number("123.4567")); //=> 123

Be aware though that Number in some cases (unexpectely) returns 0.

+null   //=> 0
+"  "   //=> 0
+""     //=> 0
+false  //=> 0
+[]     //=> 0

Tags:

Javascript