PDA

Click to See Complete Forum and Search --> : [JavaScript] parseInt BUG? "08","09"


Jhd.Honza
Oct 18th, 2003, 03:01 PM
If I try this:
<script>
for (i=0;i<10;i++)
document.write(parseInt("0"+i.toString()) + " ");
</script>
I get 0 1 2 3 4 5 6 7 0 0 ... am I missing something? :eek:

davebat
Oct 20th, 2003, 09:37 AM
just write this


for (i=0;i<10;i++)
document.write(0 + i + " ");


Not sure what was going wrong in yours, m,aybe something to do with adding a string to an integer

Jhd.Honza
Oct 20th, 2003, 12:07 PM
Well I just wanted to verify user input. I have 'Hours':'Minutes' text boxes and I think you normally enter value like "05" mins rather than "5".
As long as I need to do some mathematical operations with this value, I tried to convert it to number, using parseInt. And I found, that for values "08" and "09" it returns 0.

CornedBee
Oct 21st, 2003, 05:06 AM
A string starting with "0" is treated as an octal number. "08" starts with "0". So parseInt takes all characters up to the first invalid one (that is not in the radix's digit set) and parses them. Octal digits have the set "01234567", so the "8" is invalid. The starting "0" is stripped too, which leaves "" as the string to be parsed. Which results in 0.

CornedBee
Oct 21st, 2003, 05:07 AM
I wrote a function parseDecimal, hold on a minute.

CornedBee
Oct 21st, 2003, 05:09 AM
Wrote this when I had the same problem.
function isStringNumber(s)
{
var ret = true;
var i;
for(i=0;i<s.length;++i)
ret = ret && (s.charAt(i) == (""+parseInt(s.charAt(i))));
return ret;
}

// like parseInt, but always base 10
function parseDecimal(s)
{
var out = 0, i;
for(i=0;i<s.length;++i)
{
out *= 10;
out += parseInt(s.charAt(i));
}
return out;
}

Jhd.Honza
Oct 21st, 2003, 09:21 AM
Ok, thank you for replies, I haven't expected octal conversion :).

And I also found the most simple solution... use parseFloat ;)