March 13, 2008

parseInt returns 0 or weird numbers

Here's a time waster. Why would JavaScript's parseInt return 0 when you pass on a string like '08' ? Or 668 for '01234' ?

The reason is that the 1-parameter version tries to do it's best to figure out what radix you are using for your string. So you can have 0xCAFE for a lovely hex number (that can also wake you in the morning :) ). Guess what 01234 is ? It's an octal number because it starts with a zero.

If you want '08' to be 8, you can use the second parameter of parseInt which is the radix for the conversion.

Good luck!

0 comments:

Post a Comment