16

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
How to parseInt a string with leading 0

document.write(parseInt("07"));

Produces "7"

document.write(parseInt("08"));

Produces "0"

This is producing problems for me (sorry for this babble, I have to or I can't submit the question). Anyone know why it's being stupid or if there is a better function?

Community
  • 1
  • 1
joedborg
  • 17,651
  • 32
  • 84
  • 118

5 Answers5

25

If you argument begins with 0, it will be parsed as octal, and 08 is not a valid octal number. Provide a second argument 10 which specifies the radix - a base 10 number.

document.write(parseInt("08", 10));
Dennis
  • 32,200
  • 11
  • 64
  • 79
7

use this modification

parseInt("08",10);

rules for parseInt(string, radix)

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)
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
2

You want parseInt('08', 10) to tell it to parse as a decimal.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

You just using input parameters of that function in a bit wrong way. Check this for more info. Basically :

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

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)

So 07 and 08 is parsed into octal . That's why 07 is 7 and 08 is 0 (it is rounded to closest)

Community
  • 1
  • 1
chaZm
  • 404
  • 1
  • 3
  • 11
1

Try this :

parseInt('08', 10)

it will produce 8

Tushar Ahirrao
  • 12,669
  • 17
  • 64
  • 96