3

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 this?

Community
  • 1
  • 1
T Nguyen
  • 3,144
  • 1
  • 30
  • 43

4 Answers4

16

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).


Sarfraz
  • 367,681
  • 72
  • 526
  • 573
11

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);
TJHeuvel
  • 11,944
  • 3
  • 36
  • 46
1

Leading zeros make the number octal

James
  • 8,897
  • 2
  • 28
  • 47
1

It's an octal number

8 + 4 == 12

Omar Qureshi
  • 8,773
  • 3
  • 32
  • 35