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,309
  • 2
  • 31
  • 48

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
  • 377,238
  • 77
  • 533
  • 578
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
  • 12,403
  • 4
  • 37
  • 46
1

Leading zeros make the number octal

James
  • 9,064
  • 3
  • 31
  • 49
1

It's an octal number

8 + 4 == 12

Omar Qureshi
  • 8,963
  • 3
  • 33
  • 35