Skip to content Skip to sidebar Skip to footer

Why Does ParseInt("014") Come Out To 12?

Possible Duplicate: Workarounds for JavaScript parseInt octal bug It seems as though leading zeroes should just be ignored when parsing for an Int. What is the rationale behind

Solution 1:

It is parsed as octal number, you need to specify base too:

parseInt("014", 10)   // 14

Quoting:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).

  • If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

  • If the input string begins with any other value, the radix is 10 (decimal).



Solution 2:

Because it is parsed as an octal number, and not decimal. From MDC:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
  • If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

To force it to parse as Decimal, just supply 10 as your second argument (base).

var i = parseInt(012,10);

Solution 3:


Solution 4:

It's an octal number

8 + 4 == 12


Post a Comment for "Why Does ParseInt("014") Come Out To 12?"