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 ?

2
  • Simple googling would also have solved this: w3schools.com/jsref/jsref_parseint.asp Commented Jun 26, 2012 at 8:01
  • Googling your exact question title also brings up the answer... Commented Jun 26, 2012 at 9:45

4 Answers 4

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.)

Sign up to request clarification or add additional context in comments.

Comments

2

Also see Number:

Number("08"); // => 8

Comments

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/

Comments

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

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.