0

I am beginner of JavaScript programming, when I check for parseInt() i.e., which converts string into an Integer Number, I am getting some different outputs.

 var temp = 030;
 document.writeln(" temp value after parseInt is =" +  parseInt(temp));

 output : temp value after parseInt is =24

I did n't find the reason why it is showing 24. Could you please help me in this. Thanks

3
  • 3
    because you have prefixed with 0 so it will be interpreted as octal number Commented Mar 20, 2015 at 10:12
  • You haven't give the variable temp a string value. The correct declaration would be var temp = "030";. Commented Mar 20, 2015 at 10:12
  • possible duplicate of How to parseInt a string with leading 0 Commented Mar 20, 2015 at 12:26

4 Answers 4

2

The reason is because it is treated as octal format. Note that if the string begins with "0x", the radix is 16 (hexadecimal) and if the string begins with "0", the radix is 8 (octal).

To get the correct output just try like this:

alert(parseInt('030',10));

DEMO

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

2 Comments

“if the string begins with "0", the radix is 8 (octal)” —this is incorrect. parseInt('030',10) is still 30. You probably mean “if the number starts with 0”. Also, just wanted to mention that this hasn’t been the case before the ECMAScript 5 standard. Prior to that parseInt('030') would have resulted in 24.
@Xufox:- Yes thats a typo and I agree that this was case before ECMAScript 5.
1

because you have prefixed with 0 so it will be interpreted as octal number

so 030 will beconverted to decimal and that is 24

Comments

1

ParseInt is a method to convert a string to number. You can add a second parameter in your parseInt to spedify the mathematical base.

For example:

parseInt('030',10)

If radix is undefined or 0 (or absent), JavaScript assumes the following:

If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.

If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

If the input string begins with any other value, the radix is 10 (decimal).

Comments

0

mb u mean?:

 var temp = '030';
 document.writeln(" temp value after parseInt is =" +  parseInt(temp));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.