146
rated 0 times
[
151]
[
5]
/ answers: 1 / hits: 64229
/ 15 Years ago, mon, may 11, 2009, 12:00:00
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.
More From » integer