Take the 2-minute tour ×

Defaulting the radix to 8 (if the string starts with a 0) in JavaScript's parseInt function annoys me, only because I continue to forgot to pass the optional second argument as 10. I'm looking for an answer telling me why it makes sense to have it default to 8.

share|improve this question
add comment

3 Answers

up vote 11 down vote accepted

It only "defaults" to 8 if the input string starts with 0. This is an unfortunate carryover from C and C++.

You can use Number('0123') instead.

How do I work around JavaScript's parseInt octal behavior?

Can you tell me more about this carryover?

Note: ECMAScript strict mode removes octal syntax.

share|improve this answer
Can you tell me more about this carryover? –  Kirk Apr 8 '11 at 20:23
Yes. It is stupid, evil, bad, and obnoxious - a poorly designed "feature" implemented solely because previous languages did it. –  Matt Ball Apr 8 '11 at 20:26
A unary + is a better choice than using Number. Unary + ignores octal formats (but still honors hexadecimal formats) and is faster than a function call. –  Reid Apr 8 '11 at 20:55
@Reid: the better choice depends on your usage. As for performance, I'm not 100% sure that + is faster (and it almost certainly isn't the same for all browsers). Let's see: jsperf.com/string-to-int-2 –  Matt Ball Apr 8 '11 at 21:11
add comment

If a number starts with 0 and contains digits between (and inclusive) 0 to 7, it is interpreted as an octal number (with base 8 instead of 10).

In parseInt however, if a string starts with a 0 it's always interpeted as an octal, and stops searching when it encounters an invalid character (e.g. the digits 8 or 9 or a character like z).

parseInt("070");     //56
parseInt("70");      //70
parseInt("070", 10); //70
parseInt("78");      //78
parseInt("078");     //7, because it stops before 8

If you need to convert a string into a number, and you're sure that it contains no invalid characters or fractional parts, you can multiply it with 1 to make a number of it:

1 * "070";           //70

I personally prefer this approach, and believe it's faster than calling functions.

share|improve this answer
At least in Chrome, parseInt isn't actually that smart. parseInt('019') returns 1, and parseInt('09') returns 0. Ouch. –  Matt Ball Apr 8 '11 at 20:24
For those who do not understand what Matt Ball is talking about, the first answer submitted contained the first paragraph only. –  Lekensteyn Apr 8 '11 at 20:28
add comment

Here is an alternative to using parseInt() or Number()

If you are dealing with a string containing a number, you can multiply the string by 1.

"01"+2   //returns "012"
"01"*1+2 //returns 3
share|improve this answer
add comment

Your Answer


