Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parseInt "problem" 2

Status
Not open for further replies.

LFI

Programmer
Apr 27, 1999
1,996
US
Here's an odd one. It took me a while to find my bug because I didn't even think about THIS:

parseInt('08') returns 0 (not 8, as I would expect). Can anyone figure why this might be? I can't begin to imagine!

--Dave

P.S., try it for yourself!
Code:
<html>
<head>
<script>
alert(parseInt('08'));
</script>
</head>
</html>
 
'z8' -> NaN
' 8' -> 8
'\n8' -> 8
'89z' -> 89
'0z' -> 0
'08' -> 0

Cute. I am thinking numbers do not have leading zeros according to some deep mathematical definition somewhere.

We become accustomed to seeing 08/25/05 and thinking that means month 8. But maybe it really means code 08 for August.

When we count, we count 1, 2, 3; not 01, 02, 03. And if you wanted to, how would you decide whether to count 01, 02, 03; or 001, 002, 003; or 0001, 0002, 0003. Or which comes first 0001 or 000001? So maybe those latter are not numbers. In which case parseInt('08') is correct.

But I feel your pain. '08' sure looks like 8 to me.

Thanks.


 
LookingForInfo,

If you tell it what your "base" is it will work more like expected.

Code:
var x = '08';
alert(parseInt(x, 10));


Thanks,
 
Numbers that start with 0 are translated as octal in Javascript (and numbers starting with 0x are hexadecimal). This means that 08 and 09 are impossible, and requires defining the base as 10.

Lee
 
Well now THAT makes sense! Thanks, Lee!

--Dave
 
Lrnmore,

As many times as I've seen that advice, I have NEVER yielded to it. Now I have found a real-life instance in which I would have benefited from it! Thanks for the reminder I'm a believer now! :)

--Dave
 
Dave,

Well you'd think they would call us up here at Tek-Tips and ask how things should be done. ;)

For instance why, and I'm guessing some folks here could explain the reasoning behind this, would this ever "parse" as an integer.

Code:
var x = "089this is not an integer";
alert(parseInt(x, 10));

Logically, I'd expect that to return NaN.
But that's just me I suppose.

Thanks,
Mark
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top