[thelist] js validating numbers

Scott Brady evolt at scottbrady.net
Tue Feb 11 09:10:00 CST 2003

From: "Tom Dell'Aringa" <pixelmech at yahoo.com>
>However, it looks like they want me to validate 2 types of numbers: 1
>- that its a number, and 2 - that its a *percent* (i.e., 5.76) or
>floating point. I'm not sure my function is sufficient for this
>second part..what do you think? Should they be forced to enter 2.00
>for 2%? How would I manage forcing a percentage?

Instead of making them actually enter 2.00 instead of 2, you could do the padding for them.

First, integers are easy, because you can just compare the actual value to the parseInt() value and then pad as needed:

if (theString == parseInt(theString,10).toString())
     // They entered an integer -- make a float
     theString = parseInt(theString,10).toString() + '.00';

Now, as far as forcing a decimal value to be exactly 2 decimal places, I think you can take the parseFloat() of the string, multiply by 100.  ParseInt() that, then divide back by 100:

tmpString = parseFloat(theString) * 100;
tmpString = parseInt(theString,10);
tmpString = parseFloat(theString/100);
theString = tmpString.toString();

(Now, I don't think that will do any rounding, so if someone puts in 3.567 and you want it to be 3.57, you'll need to take that into account.  We leave that as an exercise for the reader :) )

Also, regarding checking whether something is a number or not, JavaScript has the isNaN() function, which will tell you whether a value is a number or not (well, actually, it tells you if it's NOT a number).  The examples I have show doing parseInt() or parseFloat() on the value first, but I'm not certain that's required.

I hope all this helps.

Scott Brady

More information about the thelist mailing list