86

Possible Duplicate:
Check if a variable contains a numerical value in Javascript?

How do I check if variable is an integer in jQuery?

Example:

if (id == int) { // Do this }

Im using the following to get the ID from the URL.

var id = $.getURLParam("id");

But I want to check if the variable is an integer.

2
  • 18
    The "duplicate" checks for if it's a numeric value, not if it's an integral numeric value. Subtly different. Commented Apr 22, 2012 at 18:23
  • 2
    +1 This is not a duplicate although the information in the other issue is interesting and relevant. A numeric value is not necessarily an integer. Commented May 17, 2017 at 9:32

3 Answers 3

208

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

Sign up to request clarification or add additional context in comments.

11 Comments

I like this approach too, and gave an upvote
This will subtly fail if using the Number type (which is rare, but possible)
Because Javascripts implements lazy evaluation, I would first check if it is numeric.
@bardiir: shouldn't this be if($.isNumeric(id) && Math.floor(id) == id) ... ? I mean first should check if it is numeric then if it was true, try to calculate floor or otherwise it would throw an error.
This does not work if id is a string - use '+' to force the cast, i.e.: if(Math.floor(id) == +id && $.isNumeric(id))
|
49

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

7 Comments

You should always pass the radix into parseInt. Try "08" in your solution. parseInt(n, 10)
@Hemlock - Technically isInt must always return false when passed a string like "08" since it's not a numeric value. However my function returns true when passed a string like "5". That in addition to your argument that parseInt should always be passed a radix parameter made me resolve to rewrite my function. Now I use the expression +n === n && !(n % 1) to check whether or not a number is an integer. Like before it works for all numeric test cases. However now it also filters out strings (which is what you want). Thus there is no problem of the base the number is represented in.
Just to reiterate (as per your last comment), the latest update means that any string e.g. "123" will now be rejected as an integer.
I had to change === to == because strict equality resulted in false only because the type of +n is integer, and the type of n is string - at least when I used it in my MVC project with IE 11 that was the case. The function was telling me that 1 was not an integer unless I used ==. I hope this helps someone.
@GregBarth That is by design. If you want to convert a string to an integer then use parseInt.
|
31

Use jQuery's IsNumeric method.

http://api.jquery.com/jQuery.isNumeric/

if ($.isNumeric(id)) {
   //it's numeric
}

CORRECTION: that would not ensure an integer. This would:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

6 Comments

This will be true for non-int values too. $.isNumeric(3.14) => true
@bardiir, thanks. Realized that a moment before you posted and updated it.
i'm now somewhat curious what would be faster, a regular expression like your suggestion or some type-casting like in mine :D
actually match won't work in integers: var id = 3; id.match(/^\d+$/); will not result in true but an error: TypeError: id.match is not a function this is only supported on strings, just found that while testing the speed of the solutions.
But if it's a URL param, won't it come in as a string anyway? Regardless, I added a concat to make sure it's stringified.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.