13

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
  • 16,427
  • 30
  • 80
  • 114

5 Answers5

23

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
  • 31,394
  • 10
  • 61
  • 78
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
  • 38,635
  • 35
  • 154
  • 241
2

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

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
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
  • 384
  • 2
  • 11
1

Try this :

parseInt('08', 10)

it will produce 8

Tushar Ahirrao
  • 11,761
  • 17
  • 62
  • 95