Forum Moderators: open

Message Too Old, No Replies

checking for numbers

res, or something else entirely

         

natty

10:25 am on Sep 15, 2004 (gmt 0)

10+ Year Member



hi all ,

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

Bernard Marx

12:27 pm on Sep 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<* changed *>

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]

4. After the function has returned, we test with!isNaN, not!= false, otherwise zero would not be considered a number.

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 number

var num = getNumber(str)

if(!isNaN(num))
alert(num)
else
alert("not a number")

natty

2:20 pm on Sep 15, 2004 (gmt 0)

10+ Year Member



hi ,

cheers bernard.. to the rescue as ever..
i had completely forgotten about parseFloat..

many thanks as always for your comtinued help :)