Tuesday, December 19, 2006

JavaScript: Why parseInt(08) & parseInt(09) is showing the value 0 ?

That's because "08" and "09" are invalid numbers, in octal.
The parseInt() function actually allows two arguments, the string to
parse and a radix, which is optional. This radix value allows you to
convert a binary (base 2), hexadecimal (base 16) or other base string to
a decimal integer. For example
parseInt("FF", 16);
returns 255. This is very useful for parsing things like HTML color values.
Most people aren't aware of the optional radix argument. The problem is
that if you leave it off, the function will doesn't necessarily assume
you want a decimal (base 10) conversion. Instead it checks the input
string (the first argument) and if it starts with "0x" it assumes it's a
hexadecimal value. If it starts with "0" - not followed by an "x" - it
takes it as an octal value. This follows the JavaScript convention for
numeric constants. If you code
var x = 0x18;
alert(x);
it will display 24 which is the decimal equivalent of the hex number
"18". Likewise,
var x = 014;
alert(x);
displays 12 which is the decimal value of the octal number "14".
As you should know, hexadecimal uses the digits 0-9 and the letters A-F,
16 in all. Octal is base 8, so only the digits 0-7 are valid. Hence,
"08" and "09" are not valid octal numbers and the function returns zero
just as it would for "xyz" in decimal - it's not a valid number.
To avoid this, always add the second argument, in this case
parseInt("08", 10);
returns 8 (decimal), as desired.

No comments: