var value = "08";
value = parseInt(value);
When we just go through the above script, we would expect the result as "8" should be alerted. But to all our surprise the result would be "0".
Let us analyze how this happened.
when ever the browser tries parseInt("08"), zero in front tells the browser that this is an octal (base 8) number and hence will be returned as "0".
This is the default behavior of the parseInt function, to read more about the function click here.
So what we need to do in this case?
If we just check the intellisence result for the parseInt, it will be like
So it accepts another one argument called radix, and the definition of radix is as follows
"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."
And if the radix parameter is not supplied, browser 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 in our case, browser assumed the radix as 8 and returned a value of "0". To solve this issue whenever we are calling the parseInt we should explicitly specify the radix value.