1

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug

Parsing a string using parseInt method returns invalid output .

Code :

parseInt("08");

Excepted Output :

8

Real Output :

0

Code [This returns output correctly] :

parseInt("8")

Output :

8

Why it happens ?

Community
  • 1
  • 1
kannanrbk
  • 6,964
  • 13
  • 53
  • 94

4 Answers4

3

You need to specify the base:

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

Otherwise JavaScript doesn't know if you are in decimal, hexadecimal or binary. (This is a best practise you should always use if you use parseInt.)

JJJ
  • 32,902
  • 20
  • 89
  • 102
beardhatcode
  • 4,533
  • 1
  • 16
  • 29
2

Also see Number:

Number("08"); // => 8
Community
  • 1
  • 1
Gareth
  • 133,157
  • 36
  • 148
  • 157
1

You should tell parseInt its 10 based:

parseInt("08", 10);

JavaScript parseInt() Function

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)

If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)

http://jsfiddle.net/YChK5/

CD..
  • 72,281
  • 25
  • 154
  • 163
0

Strings with a leading zero are often interpreted as octal values. Since octal means, that only numbers from 0-7 have a meaning, "08" is converted to "0". Specify the base to fix this problem:

parseInt("08", 10); // base 10

As usual, the MDN is a good source of information: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt#Octal_Interpretations_with_No_Radix

Niko
  • 26,516
  • 9
  • 93
  • 110