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,604
  • 11
  • 51
  • 88

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,246
  • 20
  • 88
  • 102
beardhatcode
  • 4,205
  • 1
  • 14
  • 27
2

Also see Number:

Number("08"); // => 8
Community
  • 1
  • 1
Gareth
  • 124,675
  • 36
  • 145
  • 155
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..
  • 68,981
  • 24
  • 147
  • 156
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,166
  • 8
  • 90
  • 108