Why does parseInt('08') return 0 in Javascript?

21 August 2012

When passing a value padded with a 0, mostly when working with time, the Javascript parseInt() function returns 0 when the value is higher than 07. Only "08" and "09" return a value of zero. 01 to 07 works fine.

parseInt('08');  // returns 0
parseInt('04');  // returns 4
parseInt('02');  // returns 2
parseInt('09');  // returns 0

Why is this? The parseInt function assumes that the value passed is an octal number. The octal system goes from 0 to 7. To tell the parseInt() function what to do, you need to use the second parameter of the function. This is the radix value (2-36) which represents the numeral system to be used. We all use and think in the decimal (10) numeral system, so this fixes your problem:

parseInt('08',10);  // returns 8
You must have JavaScript enabled to use this form!

Leave a comment!

  1. Your mail is safe with me. It's only only used to display your Gravatar image!

0 comments

Please feel free to be the first to comment on this page!

By placing a comment you let me know i'm doing a good job. It doesn't have to be constructive, just a "awesome!" makes me really happy! You contribute to a better world!