Try executing the following in JavaScript:
parseInt('01'); //equals 1
parseInt('02'); //equals 2
parseInt('03'); //equals 3
parseInt('04'); //equals 4
parseInt('05'); //equals 5
parseInt('06'); //equals 6
parseInt('07'); //equals 7
parseInt('08'); //equals 0 !!
parseInt('09'); //equals 0 !!
I just learned the hard way that JavaScript thinks the leading zero indicates an octal integer, and since there is no "8"
or "9"
in base-8, the function returns zero. Like it or not, this is by design.
What are the workarounds?
Note: For sake of completeness, I'm about to post a solution, but it's a solution that I hate, so please post other/better answers.
Update:
The 5th Edition of the JavaScript standard (ECMA-262) introduces a breaking change that eliminates this behavior. Mozilla has a good write-up.
10
(decimal) unless the number to parse is prefixed with0x
, e.g.0xFF
, in which case the base parameter defaults to 16. Hopefully, one day, this issue will be a distant memory. – Andy E May 9 '11 at 10:02+'08' === 8
? True! Maybe you really needparseInt
for your real code, but not for the above. – kojiro Dec 24 '11 at 14:04Number('08')
– OnTheFly Jan 6 '12 at 20:010
orundefined
and the string's number begins with a0
digit not followed by anx
orX
, then the implementation may, at its discretion, interpret the number either as being octal or as being decimal. Implementations are encouraged to interpret numbers in this case as being decimal." (my emphasis) – T.J. Crowder Feb 8 '12 at 10:04