How can I check that a variable is a number, either an integer or a string digit?
In PHP I could do:
if (is_int($var)) {
echo \'$var is integer\'
I'd go with
isFinite(String(foo))
See this answer for an explanation why. If you only want to accept integer values, look here.
function isNumeric( $probe )
{
return parseFloat( String( $probe ) ) == $probe;
}
I'm pretty new to javascript but it seems like typeof(blah)
lets you check if something is a number (it doesn't say true for strings). A know the OP asked for strings + numbers but I thought this might be worth documenting for other people.
eg:
function isNumeric(something){
return typeof(something) === 'number';
}
Here are the docs
and here's a few console runs of what typeof produces:
typeof(12);
"number"
typeof(null);
"object"
typeof('12');
"string"
typeof(12.3225);
"number"
one slight weirdness I am aware of is
typeof(NaN);
"number"
but it wouldn't be javascript without something like that right?!
You should use:
if(Number.isInteger(variable))
alert("It is an integer");
else
alert("It is not a integer");
you can find the reference in: Number.isInteger()