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

suresh n
  • 335
  • 1
  • 4
  • 14
  • 3
    because you have prefixed with 0 so it will be interpreted as octal number – kishan Mar 20 '15 at 10:12
  • You haven't give the variable `temp` a string value. The correct declaration would be `var temp = "030";`. – Reporter Mar 20 '15 at 10:12
  • possible duplicate of [How to parseInt a string with leading 0](http://stackoverflow.com/questions/1545164/how-to-parseint-a-string-with-leading-0) – Drew Gaynor Mar 20 '15 at 12:26

4 Answers4

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

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • _“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. – Sebastian Simon Mar 20 '15 at 10:29
  • @Xufox:- Yes thats a typo and I agree that this was case before ECMAScript 5. – Rahul Tripathi Mar 20 '15 at 10:32
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

kishan
  • 454
  • 3
  • 10
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).

Maxime
  • 45
  • 4
0

mb u mean?:

 var temp = '030';
 document.writeln(" temp value after parseInt is =" +  parseInt(temp));
Legendary
  • 2,243
  • 16
  • 26