views:

234

answers:

6

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';
}

Or:

if (is_numeric($var)) {
    echo '$var is numeric';
}

How can I do it in jQuery/JavaScript?

+4  A: 

The javascript function isNaN(variable) should do the trick. It returns true if the data is not a number.

Jamie Lewis
Also see http://www.javascripter.net/faq/numbervs.htm
Will Bickford
This is a good suggestion. FWIW, this works because strings are implicitly converted to numbers - the explicit code is: `isNaN(new Number(variable))`. Note that if you wish to restrict the code to integers, `parseInt()` will return `NaN` (testable via `isNaN()`). Be aware though that `parseInt()` will happily ignore non-numberic digits at the end of the string.
Shog9
this will accept everything which can be converted to a number, including boolean values and `'infinity'`; better use `isFinite(String(foo))`
Christoph
+1  A: 

See isNan

EDIT: Please look at what Christoph has suggested below. It makes sense to use isFinite as suggested.

shahkalpesh
`isNaN()` implicitly converts to type number so you'll get false positives!
Christoph
+2  A: 
function isNumber( input ) {
    return !isNaN( input );
}

isNumber({}) // false 

isNumber('13') // true

isNumber(13) // true

isNumber('test') // false
meder
Testing with "123a" returns a false positive - the parseInt() call is dropping the "a" but isn't updating the value nor the source field.
OMG Ponies
ah, slipped my mind.
meder
A: 
var x = 5;
if(typeof x == "number")
{
alert(x+" is a number!");
}
alb
fails for a string of digits
Shog9
+1  A: 
function isNumeric( $probe )
{
    return parseFloat( String( $probe ) ) == $probe;
}
fireeyedboy
+3  A: 

I'd go with

isFinite(String(foo))

See this answer for an explanation why. If you only want to accept integer values, look here.

Christoph
Thanks Christoph on the correction. +1
shahkalpesh