JavaScript: Extremely Short and Simple is Numeric check CodeUnit 30 JUN 2010

Here is a particularly simple and short validation check to ensure that a value received is in fact a numeric (i.e. valid number) value.

To achieve this, we are going to be making use of Javascript’s built in parseInt function to check for valid numeric strings, while the equally handy parseFloat will serve us well when checking for numbers with decimal places.

So here’s the validation code then:

//check for a numeric value
if (mynum != parseInt(mynum))
alert(mynum + ' is not a whole number');

//check for a numeric value with decimals
if (mynum == parseFloat(mynum))
alert(mynum + ' is numeric');

See, didn’t I tell you it would be short and simple? :P

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.