Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
45

This is a common Javascript gotcha with a simple solution:



Just specify the base, or 'radix', like so:



parseInt('08',10); // 8


You could also use Number:



Number('08'); // 8

[#99556] Wednesday, May 6, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;