Forum Moderators: open
im looking for a little check for a number function
at the moment i have this
function isInteger(s){
var bad=false;
var c;
for (x=0;x<s.length;x++){
c = s.charAt(x);
if (c.match(/[0-9]/) == null ¦¦ c.match(/[.]/) ==null) {
bad=true;
break;
}
}
return bad;
}
which i hope should accept decimals too
any better ideas?
tia
nat
I think this is working now...
If we're testing for numbers, we might as well get the number too.
1. Convert the string (or number) to a decimal number with the Number constructor as converter (not parseFloat, since it accepts trailing non-digits).
2. Number (and parseFloat) accept hex (0xnn) numbers, so we test to see if we would have got the same with parseFloat with explicit base 10.
3. The if comparison works for 'obviously' non-numbers because
[blue]NaN!= NaN[/blue] function getNumber(str)
{
var num = Number(str);
if( parseFloat(str,10)==num )
return num;
else
return Number.NaN;
}//eg:
var str = "0x3"
// str = "0x34" // reject hex
// str = "034" // parse lead zeros as decimal
// str = "0" // zero is a numbervar num = getNumber(str)
if(!isNaN(num))
alert(num)
else
alert("not a number")