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?

0

5 Answers 5

26

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));
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

2

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

Comments

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)

Comments

1

Try this :

parseInt('08', 10)

it will produce 8

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.