83

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.

Community
  • 1
  • 1
Kaizokupuffball
  • 2,703
  • 8
  • 38
  • 58
  • 18
    The "duplicate" checks for if it's a *numeric* value, not if it's an *integral numeric* value. Subtly different. –  Apr 22 '12 at 18:23
  • 1
    +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. – phn May 17 '17 at 09:32

3 Answers3

204

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.

Pedro Moreira
  • 961
  • 1
  • 13
  • 28
bardiir
  • 14,556
  • 9
  • 41
  • 66
  • 1
    I like this approach too, and gave an upvote – Marc Apr 22 '12 at 18:18
  • This will subtly fail if using the `Number` type (which is rare, but possible) –  Apr 22 '12 at 18:22
  • @pst i don't think you got a `Number` within a variable without you knowing about that fact but yes, this could possibly not be perfectly failsafe – bardiir Apr 22 '12 at 18:26
  • @bardiir If it's assumed that `id` is a "number", why run it through the `parse*` methods? Wouldn't it just be fair to `floor` it and see? –  Apr 22 '12 at 18:29
  • You should always use the `radix` parameter with `parseInt`. – Andrew Whitaker Apr 22 '12 at 18:30
  • @pst good call, edited it... also using jquery to check for numeric now... – bardiir Apr 22 '12 at 18:33
  • 6
    Because Javascripts implements lazy evaluation, I would first check if it is numeric. – Fokko Driesprong Jan 03 '13 at 07:50
  • @FokkoDriesprong - JavaScript doesn't implement lazy evaluation. – Aadit M Shah May 16 '13 at 00:38
  • 20
    @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. – Ashkan Aug 18 '13 at 23:29
  • 4
    This does not work if id is a string - use '+' to force the cast, i.e.: `if(Math.floor(id) == +id && $.isNumeric(id))` – MarkD Sep 19 '14 at 13:44
  • This will probably fail in the case like Math.floor(2.0)==2.0 – Musab Jul 07 '18 at 09:36
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.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • 1
    You should always pass the radix into `parseInt`. Try "08" in your solution. `parseInt(n, 10)` – Hemlock Apr 22 '12 at 21:39
  • @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. – Aadit M Shah Apr 23 '12 at 06:36
  • @AaditMShah Thanks! will prove very useful. – Llewellyn May 15 '13 at 23:33
  • 1
    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. – Matt Mitchell Jul 23 '15 at 03:14
  • 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. – Greg Barth Jul 28 '15 at 15:20
  • isInt(1.0000000000000000000001) => true! Shock and panic! – Skay Jan 12 '18 at 09:43
  • 1
    @GregBarth That is by design. If you want to convert a string to an integer then use `parseInt`. – Aadit M Shah Apr 26 '19 at 10:32
  • @Skay Nothing to be shocked about. `1.0000000000000000000001` can't be represented as a [double-precision floating-point number](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). Hence, it's stored as `1`, which is an integer. If you type `1.0000000000000000000001` in a console then you'll see that it evaluates to `1`. – Aadit M Shah Apr 26 '19 at 10:37
30

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

Marc
  • 11,403
  • 2
  • 35
  • 45
  • This will be true for non-int values too. `$.isNumeric(3.14) => true` – bardiir Apr 22 '12 at 18:15
  • @bardiir, thanks. Realized that a moment before you posted and updated it. – Marc Apr 22 '12 at 18:16
  • i'm now somewhat curious what would be faster, a regular expression like your suggestion or some type-casting like in mine :D – bardiir Apr 22 '12 at 18:17
  • 1
    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. – bardiir Apr 22 '12 at 18:22
  • 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. – Marc Apr 22 '12 at 18:24
  • Better safe than sorry :) - BTW, it's about 30% slower than my solution but it should work with number types too so now it depends on your usage context for single checks i'd recommend your solution :) – bardiir Apr 22 '12 at 18:28