In javascript: why does parseInt ("08") evaluate to zero, but parseInt (08) evaluates fine?

Possible duplicate:
Workarounds for JavaScript parseInt octal error

I would have thought it had something to do with octal parsing as it only happens on 8 or 9. It was also thought to be a Chrome bug, but it also replicates in Firefox.

Is this intentional behavior? If so, why?


source to share

3 answers

The solution here is simple. NEVER call parseInt()

without specifying the desired value. When you don't pass this second parameter, it parseInt()

tries to guess that the radix is ​​based on the number format. When he guesses, he is often wrong.

Give a radius like this and you get the desired result:

parseInt("08", 10) == 8;


As for the rules it uses to guess, you can refer to the MDN docparseInt()

page for .

If radix is ​​undefined or 0, JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", the radius is 16 (Hexadecimal).
  • If the input string starts with "0", then the radius is eight (Octal). This feature is non-standard and some implementations intentionally do not support it (they use radix 10 instead). For this, a Reason is always specified when using parseInt.
  • If the input string starts with any other value, the radius is 10 (decimal). If the first character cannot be converted to a number, parseInt returns NaN.

So, according to these rules, it parseInt()

will consider that it "08"

is octal, but then it encounters a digit that is not allowed in octal, so it returns 0


When you pass a number before parseInt()

, it has nothing to do, because the value is already a number, so it doesn't try to change it.



"Is this intentional behavior?"


"If so, why?"

Leading 0

is the notation used to represent the octal number defined in the specification. The symbols 8

and 9

do not exist in octal numbering, so it parseInt

uses the first valid number it finds, which is 0


If you do ...



... the result will be ...



... because a valid number was found at the beginning of the line. Anything that is invalid outside of this is discarded.



You can fix it like this:





All Articles