...

View Full Version : why does this return 8?



code-in-time
06-22-2012, 11:05 AM
Hi, please can you help

Why do these return 8 and not 10?

how do I make 010 turn into 10 or 00000012 turn into 12



Number(010); // return 8
parseInt("010"); //returns 8


Thanks

Philip M
06-22-2012, 01:33 PM
Hi, please can you help

Why do these return 8 and not 10?

how do I make 010 turn into 10 or 00000012 turn into 12



Number(010); // return 8
parseInt("010"); //returns 8


Thanks

Because when you use parseInt() you must specify the radix. The default is normally decimal, but if a number-string begins with 0 it is interpreted as octal.

alert (parseInt("010",10)); //returns 10
alert (parseInt("000000012",10)); // returns 12

Likewise, Number(010) returns 8 (decimal) because the zero prefix means it is (correctly) interpreted as octal.

You should never precede a number with a zero unless you are specifically looking for an octal conversion!

It's a classic case of throwing out the baby with the dishwasher. Caller, BBC Radio 4

felgall
06-22-2012, 10:12 PM
Likewise, Number(010) returns 8 (decimal) because the zero prefix means it is (correctly) interpreted as octal.

Only in some browsers and only if you are not running the JavaScript in Strict mode.

In strict mode all the octal defaults are turned off because they were only implemented that way in some browsers and so some browsers report '080' as 8 while others report it as 10. Once all browsers support Strict mode then you will be able to always get 10 as the result (not that you should be using parseInt to convert it in that instance anyway.

parseInt is for converting numbers to base 10 so where it is supplied with a number that it recognises as being in a different number base it will do what it is intended for and convert it.

rnd me
06-22-2012, 11:36 PM
"00000012 "*1 == 12 //true

felgall
06-22-2012, 11:48 PM
"00000012 "*1 == 12 //true

That's because you don't have it wrapped inside a parseInt call in an attempt to convert from one number base to another.


parseInt("00000012 ") == 12 //sometimes true
parseInt("00000012 ") == 10 //sometimes true



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum