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

Related Posts:

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.

  • 4thfloorstudios

    Hi,
    I think you are disregarding that:

    parseInt(“123nonumber”)

    would return 123 :)

  • Anonymous

    if you are using jQuery and then good news is that jQuery 1.7 is released and it has a built-in function called “isNumeric()” that returns true for numeric value, otherwise false.

    Visit this article…

    http://jquerybyexample.blogspot.com/2011/11/jqueryisnumeric-in-jquery-17.html

  • Anonymous

    if you are using jQuery and then good news is that jQuery 1.7 is released and it has a built-in function called “isNumeric()” that returns true for numeric value, otherwise false.

    Visit this article…

    http://jquerybyexample.blogspot.com/2011/11/jqueryisnumeric-in-jquery-17.html

  • Masked_Avenger

    After messing around with Jquery .isNumeric() and failing to achieve what I wanted, this method has proven to be very useful and creative. Thanks