faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

496 of 507 people (98%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

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

Apr 4th, 2008 21:11
ha mo, Mike Hall, Manoj S.N., http://developer.netscape.com/docs/manuals/js/core/jsref15/toplev.html#1064173


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.
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com