38

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?

Richard Knop
  • 81,041
  • 149
  • 392
  • 552
  • I'm assuming that you are trying to avoid a round-trip to your server to test? That would be the brain-dead-easy way ;) – Will Bickford Aug 29 '09 at 22:51

10 Answers10

45

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

AAA
  • 4,928
  • 1
  • 24
  • 20
  • 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 Aug 29 '09 at 23:05
  • 1
    this will accept everything which can be converted to a number, including boolean values and `'infinity'`; better use `isFinite(String(foo))` – Christoph Aug 30 '09 at 10:43
  • 4
    Don't use isNaN, it's broken. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isNaN and use the solution proposed by @Christoph instead. – nullability Mar 18 '13 at 18:52
27

I'd go with

isFinite(String(foo))

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

Community
  • 1
  • 1
Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 7
    Watch out for this. `isFinite(null) === true` – Ryan Kirkman Sep 04 '13 at 22:58
  • 1
    isFinite("100") is true, we want to know that an object is a Number object. From my brief testing it looks like the solution here (Object.prototype.toString.call(obj) === "[object Number]") is the best: http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript – Skystrider Aug 24 '15 at 19:59
  • 1
    Also returns true with an empty string, which I wouldn't consider a "number" – Balmipour Apr 01 '17 at 23:15
  • Object.prototype.toString.call(obj) === "[object Number]" will return true if passing NaN – Luoruize Sep 07 '17 at 07:16
  • 1
    Does not handle all variables: `isFinite(String(" ")) == isFinite(String("\t")) == isFinite(String("")) == true`. See the answer linked. – cdosborn Jan 31 '18 at 16:58
  • I think `Number.isFinite()` is what you want. Behaves correctly with `null` and `''` – dlsso Jan 27 '21 at 20:00
13

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?!

JonnyRaa
  • 7,559
  • 6
  • 45
  • 49
  • 1
    It's better JS style to use `typeof(something) == 'number'`. With `==` rather than `===`. Reserve `===` for when you really mean it. – Adam Chalcraft Feb 22 '20 at 23:35
  • 3
    @AdamChalcraft most linters/programmers would probably disagree and say the opposite - always use `===` unless there's a good reason not to, if you'll get into the habit of using `==` you'll get burned by something bizaare happening at some point. In this case there's no type coercion going on so it's a fairly moot point either way. For an educational (and also hilarious) rant on the topic check out James Mickens' "To wash it all away" http://scholar.harvard.edu/files/mickens/files/towashitallaway.pdf – JonnyRaa Mar 02 '20 at 12:57
4

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()

Mechisso
  • 41
  • 2
1
function isNumeric( $probe )
{
    return parseFloat( String( $probe ) ) == $probe;
}
Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
1

You should use:

var x = 23;
var y = 34hhj;

isNaN(x); 
isNaN(y); 

It will return true if its string and false if its a number.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
Kuldeep Singh
  • 199
  • 1
  • 11
0

You should use

simple way to check whether given value is number by using "if condition"

function isInteger(value)      
{       
    num=value.trim();         
    return !(value.match(/\s/g)||num==""||isNaN(num)||(typeof(value)=='number');        
}

it will return true if the value which we are passing is an integer..

solved for     
value=""      //false null     
value="12"    //true only integers       
value="a"     //false     
value=" 12"   //false      
value="12 "   //false         
value=" "     //false space        
value="$12"   //false special characters 
value="as12"    //false
Skull
  • 1,204
  • 16
  • 28
0

Be aware that empty string '' and ' ' will be considered as number by isNaN and isFinite.

AnomalySmith
  • 597
  • 2
  • 5
  • 16
0

You should use: $.isNumeric( i )

jQuery.isNumeric API

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
FenixAdar
  • 57
  • 1
  • 2
0

The typeof operator returns a string indicating the type of the unevaluated operand.

const num = 42;
console.log(typeof num === "number"); // expected return true
if(typeof num === "number"){
   console.log("This is number")
}

More on it......

console.log(typeof 42);
// expected output: "number"

console.log(typeof 'blubber');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof undeclaredVariable);
// expected output: "undefined"
MD SHAYON
  • 7,001
  • 45
  • 38