JavaScript isNumeric function
The other day I needed to check a value to make sure it's numeric, using JavaScript (it was an Ajax app). I poked around online and a few sites said that JS doesn't have such a function. I also found a few sites that offered an isNumeric function, but most of them didn't check for decimals and/or negatives. So I created my own using a Regular Expression:
// I use this function like this: if (isNumeric(myVar)) { }
// regular expression that validates a value is numeric
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452.
// compare the argument to the RegEx
// the 'match' function returns 0 if the value didn't match
var result = x.match(RegExp);
return result;
}
Jake Munson
34 Yrs old
/^[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b/
Handles the end decimal and some other things :)
/^[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?$/
or
/^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/
if you prefer
Anyway, kudos on publishing this. I should have remembered it without looking it up.
I searched for it!
var result = x.match(RegExp);
//new
if (result==null) result=false;
//new
return result;
function isNumber( value )
{
return isFinite( (value * 1.0) );
}
function IsNumeric(n){if(n*1==n)return true;else return false;}
any non numeric value = NaN when multiplied by 1 thus altering the value of n
could use this too...
function IsNumeric(n){if(n*1==NaN)return false;else return true;}
with return result !== null;