PDA

View Full Version : Something stupid about parseInt()


ConfusedOfLife
04-26-2003, 09:54 AM
Look at this snippet:


<script>
alert( parseInt("02") );
alert( parseInt("08") );
alert( parseInt("09") );
</script>


I noticed that if you try to parseInt("08") or parseInt("09"), you only get 0 back! But for other numbers we don't have this problem! What do you think?! :rolleyes:

Algorithm
04-26-2003, 10:50 AM
When you parse a numeric string that starts with 0, JavaScript interprets it as an octal (base-8) number. Since 8 and 9 aren't numbers in the octal system, they'll be ignored.

You can get around this quite easily by specifying the radix in the call to parseInt, like so:

parseInt("09", 10); // Parse as a base-10 number

ConfusedOfLife
04-27-2003, 05:42 AM
Thank you Algorithem, you made my life really easier!