503

How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:

<html>
    <head>
        <script type="text/javascript">
            var data = 22;
            alert(NaN(data));
        </script>
    </head>
</html>
JBa
  • 5,261
  • 3
  • 14
  • 9
  • 3
    One posiblity here is to use [`parseInt`](http://www.bing.com/search?q=javascript+parseint&form=MOZSBR&pc=MOZI). – Paul Jan 31 '13 at 22:50
  • 3
    http://jsben.ch/#/htLVw - a benchmark for the common ways to do it – EscapeNetscape Oct 24 '16 at 17:44
  • 2
    All the answers here are really outdated. Today, I recommend sticking to `Number.isInteger` which is the least hacky way. – Benjamin Gruenbaum Feb 25 '18 at 13:35
  • 3
    @Benjamim what if the number is a string that can be converted to a integer? and in HTML everything is a string.. so Number.isInteger("69") is false – joedotnot Oct 31 '18 at 08:19

41 Answers41

590

That depends, do you also want to cast strings as potential integers as well?

This will do:

function isInt(value) {
  return !isNaN(value) && 
         parseInt(Number(value)) == value && 
         !isNaN(parseInt(value, 10));
}

With Bitwise operations

Simple parse and check

function isInt(value) {
  var x = parseFloat(value);
  return !isNaN(value) && (x | 0) === x;
}

Short-circuiting, and saving a parse operation:

function isInt(value) {
  if (isNaN(value)) {
    return false;
  }
  var x = parseFloat(value);
  return (x | 0) === x;
}

Or perhaps both in one shot:

function isInt(value) {
  return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}

Tests:

isInt(42)        // true
isInt("42")      // true
isInt(4e2)       // true
isInt("4e2")     // true
isInt(" 1 ")     // true
isInt("")        // false
isInt("  ")      // false
isInt(42.1)      // false
isInt("1a")      // false
isInt("4e2a")    // false
isInt(null)      // false
isInt(undefined) // false
isInt(NaN)       // false

Here's the fiddle: http://jsfiddle.net/opfyrqwp/28/

Performance

Testing reveals that the short-circuiting solution has the best performance (ops/sec).

// Short-circuiting, and saving a parse operation
function isInt(value) {
  var x;
  if (isNaN(value)) {
    return false;
  }
  x = parseFloat(value);
  return (x | 0) === x;
}

Here is a benchmark: http://jsben.ch/#/htLVw

If you fancy a shorter, obtuse form of short circuiting:

function isInt(value) {
  var x;
  return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
}

Of course, I'd suggest letting the minifier take care of that.

Davide Pizzolato
  • 679
  • 8
  • 25
krisk
  • 6,957
  • 1
  • 18
  • 30
  • 9
    @krisk - Upvoted for multiple solutions. Also performed a quick test on the 4 variants you provided: http://jsperf.com/tfm-is-integer - and determined that the short-circuiting solution has the best performance. – tim-montague Jun 01 '15 at 06:15
  • Since bitwise op returns 0 for a NaN, you could maybe dispense with the short circuit. I don't know however what are the respective costs of bitwising a NaN and isNan. – Éric Viala Jun 14 '15 at 21:31
  • will it return true for 2.00 ? – Yash Sharma Jun 20 '17 at 12:22
  • 3
    It's returning false on 2099999999999999 :-*(* – jkucharovic Jun 26 '17 at 11:35
  • 1
    @jkucharovic the bitwise OR operator is the culprit. Using the non-bitwise version will return true. – krisk Jun 26 '17 at 18:33
  • 2
    This makes '2.' evaluate to true – cyberwombat Jun 27 '17 at 16:19
  • 1
    @cyberwombat well that is a decimal number 2.0 :-) – Kuba Beránek Feb 02 '18 at 13:10
  • @KubaBeránek I guess its unclear what OP wants. In my case '2' is a string and therefore not an integer. – cyberwombat Feb 02 '18 at 15:54
  • 1
    @cyberwombat if you just want to check the datatype, typeof is enough (you can combine it with isNaN) – Kuba Beránek Feb 03 '18 at 19:46
  • what if I want it to return false for the 4e2? – J_rite Jun 06 '18 at 11:38
  • There is an issue in this code. Running your fiddle and running values as low as 10000000000 starts to break the check. However the max safe integer in javascript is: 9007199254740990, which is far larger. – Ryan Rentfro Aug 13 '18 at 04:49
  • it says that 0xf7f is true. – Florian Bauer Aug 29 '18 at 11:41
  • bitwise won´t work with numbers bigger than 32 bits and javascript can represent integers up to 53bits: "The operands of all bitwise operators are converted to signed 32-bit integers" (MDN) Number.MAX_SAFE_INTEGER is 2^53 -1 – repeatdomiau Mar 09 '19 at 09:54
  • @krisk This Answer is Mentioned in the AngularJS Source file. – Jenson M John Jun 19 '19 at 19:08
  • 1
    @JensonMJohn, found it: https://github.com/angular/angular.js/blob/65f800e19ec669ab7d5abbd2f6b82bf60110651a/src/ng/directive/input.js#L1665 Thanks for pointing it out :) – krisk Jun 21 '19 at 01:43
  • 1
    `const s = Symbol('sym'); isInt(s); ` or `const o = Object.create(null) isInt(o)` These calls will throw an exception. They should be handled properly. – Yaki Klein Sep 16 '19 at 08:32
  • This returns `true` for string and number decimals. `4.00 // true` and `'4.00' //true` – James Oct 23 '20 at 12:25
  • Why was the !isNaN(parseInt(value, 10)) included. Also I was using typescript and thought of only including !isNaN(value) && parseInt(Number(value)) === value – Chief Sep 17 '22 at 09:33
385

Use the === operator (strict equality) as below,

if (data === parseInt(data, 10))
    alert("data is integer")
else
    alert("data is not an integer")
Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
pranag
  • 5,432
  • 2
  • 17
  • 15
  • 2
    if you run your example through the above code it alerts out a as an integer and the other as not an integer which is the case... in case of NaN also the type of NaN is different from the type of the return value of pareInt()..... – pranag Feb 01 '13 at 15:21
  • 1
    could you elaborate a bit? the "example" is only demonstrating that using parseInt yields worse performance than using typeof keyword and modulus operator. but I do see what you mean now about (NaN != NaN) – Blake Regalia Feb 01 '13 at 22:35
  • `parseInt(2.0) === 2.0` – connorbode Jul 03 '14 at 16:19
  • 6
    @connorbode in javascript all numbers have the same type (there is no float or double), so `2.0 === 2` since the unnecessary decimal is just a different representation of the same number, thus `parseInt(2.0) === 2.0` is equivalent to `parseInt(2) === 2` which is true – Michael Theriot Aug 21 '14 at 09:38
  • 1
    @BlakeRegalia: Although being fast his method **does not** pass all possible values from this answer: http://stackoverflow.com/a/14794066/843732 – c00000fd Sep 09 '14 at 19:23
  • 1
    Problem: set variable a = "2" then a === parseInt(a) returns false – Quadrivium Oct 06 '14 at 18:39
  • This isn't a safe answer. The only cross platform solution for this is using the modulus operator as noted by François Wahl below. – deepelement Nov 27 '14 at 12:53
  • parseInt transforms "40 is a number" into an integer 40, while "This 40 is stupid" is NaN. – dube May 20 '15 at 15:37
  • 4
    This is a bad idea. See http://www.2ality.com/2014/05/is-integer.html (1.4). `parseInt()` coerces to string, for large numbers it won't do what you expect: `console.log(1000000000000000000000);` => `1e+21`. There's plenty of better ways, e.g. `const isInteger = val => val%1==0`. – joerx Oct 22 '16 at 06:30
  • 1
    The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe: String(1000000000000000000000) '1e+21' parseInt(1000000000000000000000, 10) 1 parseInt(1000000000000000000000, 10) === 1000000000000000000000 false https://stackoverflow.com/a/45037143/5470829 – Sona Jul 11 '17 at 14:24
  • this is actually wrong for where data has non-number prefixes.. why not just: `if (data === parseInt(data, 10).toString())` – formiaczek Aug 20 '20 at 09:10
  • 2
    I'd vote for this answer to be removed altogether. – Dmitry Shvedov Mar 25 '21 at 22:30
155

Number.isInteger() seems to be the way to go.

MDN has also provided the following polyfill for browsers not supporting Number.isInteger(), mainly all versions of IE.

Link to MDN page

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" && 
           isFinite(value) && 
           Math.floor(value) === value;
};
Nisala
  • 1,313
  • 1
  • 16
  • 30
Walter Roman
  • 4,621
  • 2
  • 32
  • 36
  • 2
    MDN has the test on 9007199254740992 [removed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger$compare?locale=en-US&to=814547&from=679289) – Bernhard Döbler Jul 30 '15 at 10:43
  • 6
    This is the most straightforward and "correct" answer. I mean, JavaScript already has the method to check for integerhood. No need to write a new one. isNaN() tests for numericity, not integerhood. – globewalldesk Jan 29 '19 at 16:28
  • 4
    @globewalldesk Maybe it answers the question "how to check if a number is integer" but not "if a variable is integer". E.g. a string "1" for example. – Onkeltem Nov 12 '20 at 11:52
  • @Onkeltem `Number.isInteger("1")` – Walter Roman Nov 13 '20 at 09:55
  • @WalterRoman why? It returns `false`, while I would expect `true`. For example, parse a string like `product/24/edit`. After parsing you get an array like `["product", 24, "edit"]`, where `"24"` is most likely the integer of `24`. – Onkeltem Nov 13 '20 at 15:14
  • Fix to the above. Should read: `["product", "24", "edit"]` – Onkeltem Nov 13 '20 at 15:24
  • @Onkeltem `Number.isInteger(parseInt("1"))` returns true – Walter Roman Dec 08 '20 at 16:23
  • 1
    I find it useful to do `Number.isInteger(parseFloat(value))` for form validations. Things magically change from number to string and back sometimes when dealing with forms. – Dmitry Shvedov Mar 25 '21 at 22:28
  • @BernhardDöbler do you want to show the max. number for `Number.isinteger()`? – Timo Mar 27 '21 at 19:13
  • return Number.isFinite() && Math.floor(value) === value; is more coincise – Nick Oct 12 '21 at 17:30
  • @WalterRoman `parseInt('123abc')` will become `123`, thus invalidating your method. – Rodrigo Jan 15 '23 at 00:08
128

Assuming you don't know anything about the variable in question, you should take this approach:

if(typeof data === 'number') {
    var remainder = (data % 1);
    if(remainder === 0) {
        // yes, it is an integer
    }
    else if(isNaN(remainder)) {
        // no, data is either: NaN, Infinity, or -Infinity
    }
    else {
        // no, it is a float (still a number though)
    }
}
else {
    // no way, it is not even a number
}

To put it simply:

if(typeof data==='number' && (data%1)===0) {
    // data is an integer
}
Blake Regalia
  • 2,677
  • 2
  • 20
  • 29
  • 8
    What do you mean? This checks for data types in javascript, `"1.0"` is a string, and is therefore not a number. Otherwise `1` will be the value of a variable if you set it thusly `var my_var=1.0;`, which is correctly identified by this function as an integer. – Blake Regalia Feb 06 '14 at 19:36
  • 5
    Soon, [`Number.isInteger()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger) will work... until then, this is a good way to do it – Claudiu Apr 29 '16 at 20:21
  • Number.isInteger doesn't work for me. I must be doing something wrong. Blake's solution %1 works perfectly. – mcmacerson Sep 21 '17 at 15:56
81

You could check if the number has a remainder:

var data = 22;

if(data % 1 === 0){
   // yes it's an integer.
}

Mind you, if your input could also be text and you want to check first it is not, then you can check the type first:

var data = 22;

if(typeof data === 'number'){
     // yes it is numeric

    if(data % 1 === 0){
       // yes it's an integer.
    }
}
Nope
  • 22,147
  • 7
  • 47
  • 72
30

You can use a simple regular expression:

function isInt(value) {
    var er = /^-?[0-9]+$/;
    return er.test(value);
}
Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
29

In ES6 2 new methods are added for Number Object.

In it Number.isInteger() method returns true if the argument is an integer, otherwise returns false.

Important Note: The method will also return true for floating point numbers that can be represented as integer. Eg: 5.0 (as it is exactly equal to 5 )

Example usage :

Number.isInteger(0);         // true
Number.isInteger(1);         // true
Number.isInteger(-100000);   // true
Number.isInteger(99999999999999999999999); // true

Number.isInteger(0.1);       // false
Number.isInteger(Math.PI);   // false

Number.isInteger(NaN);       // false
Number.isInteger(Infinity);  // false
Number.isInteger(-Infinity); // false
Number.isInteger('10');      // false
Number.isInteger(true);      // false
Number.isInteger(false);     // false
Number.isInteger([1]);       // false

Number.isInteger(5.0);       // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true
Arun Joseph
  • 2,736
  • 25
  • 35
22

First off, NaN is a "number" (yes I know it's weird, just roll with it), and not a "function".

You need to check both if the type of the variable is a number, and to check for integer I would use modulus.

alert(typeof data === 'number' && data%1 == 0);
Phil
  • 6,686
  • 2
  • 19
  • 25
14

Be careful while using

num % 1

empty string ('') or boolean (true or false) will return as integer. You might not want to do that

false % 1 // true
'' % 1 //true

Number.isInteger(data)

Number.isInteger(22); //true
Number.isInteger(22.2); //false
Number.isInteger('22'); //false

build in function in the browser. Dosnt support older browsers

Alternatives:

Math.round(num)=== num

However, Math.round() also will fail for empty string and boolean

vsync
  • 118,978
  • 58
  • 307
  • 400
Jhankar Mahbub
  • 9,746
  • 10
  • 49
  • 52
9

To check if integer like poster wants:

if (+data===parseInt(data)) {return true} else {return false}

notice + in front of data (converts string to number), and === for exact.

Here are examples:

data=10
+data===parseInt(data)
true

data="10"
+data===parseInt(data)
true

data="10.2"
+data===parseInt(data)
false
user603749
  • 1,638
  • 2
  • 24
  • 36
  • 7
    This seems like the smartest solution for my case (where I don't mind if it's an integer in a string). However: why not just go `return (+data===parseInt(data))`? – Swiss Mister Jul 31 '14 at 14:22
7

Check if the variable is equal to that same variable rounded to an integer, like this:

if(Math.round(data) != data) {
    alert("Variable is not an integer!");
}
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • You can very easily fix this function's issue with returning `true` for `NaN`, by simply changing `!=` to `!==` and inverting the `if` blocks. This works because `NaN` is the only value in JavaScript that does not equal itself. For example, the new code should be `if (Math.round(x) === x) { /* x IS an integer! */ }` – mgthomas99 Dec 04 '17 at 14:46
6

The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:

function isInteger(x) { return (x^0) === x; } 

The following solution would also work, although not as elegant as the one above:

function isInteger(x) { return Math.round(x) === x; }

Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.

Or alternatively:

function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

One fairly common incorrect solution is the following:

function isInteger(x) { return parseInt(x, 10) === x; }

While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:

> String(1000000000000000000000)
'1e+21'

> parseInt(1000000000000000000000, 10)
1

> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false
6

Why hasnt anyone mentioned Number.isInteger() ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

Works perfectly for me and solves the issue with the NaN beginning a number.

4b0
  • 21,981
  • 30
  • 95
  • 142
nights
  • 411
  • 3
  • 9
  • 3
    Note that this is ES6, so [older browsers (like IE <= 11) don't support it.](https://caniuse.com/#search=isNaN) The docs above provide a polyfill. – bishop Jul 14 '18 at 00:07
  • 1
    Somebody did mention `Number.isInteger()`, 3.5 years before you: https://stackoverflow.com/a/27424770/5208540 – Alex Stragies Jul 15 '18 at 00:50
  • if we are going to catch an value from an input then check, Number.isInteger will always return false as the input value is of string datatype – Shinigamae Nov 13 '18 at 08:53
5
if(Number.isInteger(Number(data))){
    //-----
}
guest
  • 59
  • 1
  • 1
  • 1
    Same comment as below: [Not supported by IE and Safari](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger). – crisscross Jul 19 '17 at 13:44
  • @crisscross Now supported by everything except IE, which is only a concern if you're supporting legacy operating systems. – faintsignal Sep 21 '17 at 16:59
  • Number(data) would be zero if data is empty string or null, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#convert_numeric_strings_and_null_to_numbers – AJ H Mar 04 '21 at 09:25
4

ECMA-262 6.0 (ES6) standard include Number.isInteger function.

In order to add support for old browser I highly recommend using strong and community supported solution from:

https://github.com/paulmillr/es6-shim

which is pure ES6 JS polyfills library.

Note that this lib require es5-shim, just follow README.md.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
4

The Accepted answer not worked for me as i needed to check for int/float and alphabet. so try this at will work for both int/float and alphabet check

function is_int(value){
        if( (parseInt(value) % 1 === 0 )){
            return true;
        }else{
            return false;
        }
}

usage

is_int(44);   // true
is_int("44");   // true
is_int(44.55);  // true
is_int("44.55");  // true
is_int("aaa");  // false  
user889030
  • 4,353
  • 3
  • 48
  • 51
3

You could use this function:

function isInteger(value) {
    return (value == parseInt(value));
}

It will return true even if the value is a string containing an integer value.
So, the results will be:

alert(isInteger(1)); // true
alert(isInteger(1.2)); // false
alert(isInteger("1")); // true
alert(isInteger("1.2")); // false
alert(isInteger("abc")); // false
ferhrosa
  • 1,714
  • 2
  • 11
  • 6
3

Use the | operator:

(5.3 | 0) === 5.3 // => false
(5.0 | 0) === 5.0 // => true

So, a test function might look like this:

var isInteger = function (value) {
  if (typeof value !== 'number') {
    return false;
  }

  if ((value | 0) !== value) {
    return false;
  }

  return true;
};
Golo Roden
  • 140,679
  • 96
  • 298
  • 425
3

Number.isInteger() is the best way if your browser support it, if not, I think there are so many ways to go:

function isInt1(value){
  return (value^0) === value
}

or:

function isInt2(value){
  return (typeof value === 'number') && (value % 1 === 0); 
}

or:

function isInt3(value){
  return parseInt(value, 10) === value; 
}

or:

function isInt4(value){
  return Math.round(value) === value; 
}

now we can test the results:

var value = 1
isInt1(value)   // return true
isInt2(value)   // return true
isInt3(value)   // return true
isInt4(value)   // return true

var value = 1.1
isInt1(value)   // return false
isInt2(value)   // return false
isInt3(value)   // return false
isInt4(value)   // return false

var value = 1000000000000000000
isInt1(value)   // return false
isInt2(value)   // return true
isInt3(value)   // return false
isInt4(value)   // return true

var value = undefined
isInt1(value)   // return false
isInt2(value)   // return false
isInt3(value)   // return false
isInt4(value)   // return false

var value = '1' //number as string
isInt1(value)   // return false
isInt2(value)   // return false
isInt3(value)   // return false
isInt4(value)   // return false

So, all of these methods are works, but when the number is very big, parseInt and ^ operator would not works well.

Wilt
  • 41,477
  • 12
  • 152
  • 203
  • Having the following test `let possibleDataTypes = ['string', '20', '20.000','20.0001', [], {}, new Number(5), NaN, null, undefined, Infinity, -Infinity, true, false, 20, -20, 200000000, 20.000000, 20.000001 , Math.PI, 100000000000000000000, 1 + 1e-16]; let polyFillFunctions = [isInt1, isInt2, isInt3, isInt4, Number.isInteger]; possibleDataTypes.map((dataType) =>{console.log(polyFillFunctions.map((functionName) => functionName(dataType))) });` display the possible data types' output in a compact side-by-side pseudo-tabular format. Inconsistent results arose. – polendina Sep 01 '22 at 09:25
3

You could tryNumber.isInteger(Number(value)) if value might be an integer in string form e.g var value = "23" and you want this to evaluate to true. Avoid trying Number.isInteger(parseInt(value)) because this won't always return the correct value. e.g if var value = "23abc" and you use the parseInt implementation, it would still return true.

But if you want strictly integer values then probably Number.isInteger(value) should do the trick.

gbozee
  • 4,366
  • 1
  • 23
  • 23
  • 1
    Note that this is not supported by IE; as stated [here in the docu](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger) I got my scrip halted because of this especially if the var you are checking is undefined – mikewasmike Jul 12 '17 at 14:55
3
var x = 1.5;
if(!isNaN(x)){
 console.log('Number');
 if(x % 1 == 0){
   console.log('Integer');
 }
}else {
 console.log('not a number');
}
Hemant
  • 391
  • 1
  • 2
  • 10
3

My approach:

a >= 1e+21 → Only pass for very large numbers. This will cover all cases for sure, unlike other solutions which has been provided in this discussion.

a === (a|0) → if the given function's argument is exactly the same (===) as the bitwise-transformed value, it means that the argument is an integer.

a|0 → return 0 for any value of a that isn't a number, and if a is indeed a number, it will strip away anything after the decimal point, so 1.0001 will become 1

const isInteger = n => n >= 1e+21 ? true : n === (n|0);

// tests:
[
  [1,                         true],
  [1000000000000000000000,    true],
  [4e2,                       true],
  [Infinity,                  true],
  [1.0,                       true],
  [1.0000000000001,           false],
  [0.1,                       false],
  ["0",                       false],
  ["1",                       false],
  ["1.1",                     false],
  [NaN,                       false],
  [[],                        false],
  [{},                        false],
  [true,                      false],
  [false,                     false],
  [null,                      false],
  [undefined,                 false],
].forEach(([test, expected]) => 
  console.log(
    isInteger(test) === expected, 
    typeof test, 
    test
   ) 
)
vsync
  • 118,978
  • 58
  • 307
  • 400
  • 1
    Good idea! I also like that you showed your tests but unfortunately this does not consider a String value of "0". – Jammer Nov 12 '18 at 13:08
  • Hey @vsync, Not intentionally. I did originally upvote but decided to revert it back due to my previous comment. I must have accidentally double clicked it or something. – Jammer Nov 13 '18 at 01:54
  • 1.0 is a float, not an integer – scavenger Nov 12 '22 at 18:40
3

Just try this:

let number = 5;
if (Number.isInteger(number)) {
    //do something
}
Jan WebDev
  • 69
  • 4
  • Number.isInteger() is not supported in all versions of IE browsers. – S K R Feb 20 '20 at 10:31
  • depends... if you care about preservation of Neanderthal Technology or if you want to promote new technologies. If you embrace the future then you would indeed adopt ES6 and do all you can to destroy IE. Like I do, like most do :) – scavenger Nov 12 '22 at 18:46
3

What about large integers (bigint)?

Most of these answers fail on large integers (253 and larger): Bitwise tests(e.g. (x | 0) === x), testing typeof x === 'number', regular int functions (e.g. parseInt), regular arithmetics fail on large integers. This can be resolved by using BigInt.

I've compiled several answers into one snippet to show the results. Most outright fail with large integers, while others work, except when passed the type BigInt (e.g. 1n). I've not included duplicate answers and have also left out any answers that allow decimals or don't attempt to test type)

// these all fail
n = 1000000000000000000000000000000
b = 1n

// These all fail on large integers
//https://stackoverflow.com/a/14636652/3600709
console.log('fail',1,n === parseInt(n, 10))
//https://stackoverflow.com/a/14794066/3600709
console.log('fail',2,!isNaN(n) && parseInt(Number(n)) == n && !isNaN(parseInt(n, 10)))
console.log('fail',2,!isNaN(n) && (parseFloat(n) | 0) === parseFloat(n))
console.log('fail',2,!isNaN(n) && (function(x) { return (x | 0) === x; })(parseFloat(n)))
//https://stackoverflow.com/a/21742529/3600709
console.log('fail',3,n == ~~n)
//https://stackoverflow.com/a/28211631/3600709
console.log('fail',4,!isNaN(n) && parseInt(n) == parseFloat(n))
//https://stackoverflow.com/a/41854178/3600709
console.log('fail',5,String(parseInt(n, 10)) === String(n))

// These ones work for integers, but not BigInt types (e.g. 1n)
//https://stackoverflow.com/a/14636725/3600709
console.log('partial',1,typeof n==='number' && (n%1)===0) // this one works
console.log('partial',1,typeof b==='number' && (b%1)===0) // this one fails
//https://stackoverflow.com/a/27424770/3600709
console.log('partial',2,Number.isInteger(n)) // this one works
console.log('partial',2,Number.isInteger(b)) // this one fails
//https://stackoverflow.com/a/14636638/3600709
console.log('partial',3,n % 1 === 0)
console.log('partial',3,b % 1 === 0) // gives uncaught type on BigInt

Checking type

If you actually want to test the incoming value's type to ensure it's an integer, use this instead:

function isInt(value) {
    try {
        BigInt(value)
        return !['string','object','boolean'].includes(typeof value)
    } catch(e) {
        return false
    }
}

function isInt(value) {
    try {
        BigInt(value)
        return !['string','object','boolean'].includes(typeof value)
    } catch(e) {
        return false
    }
}

console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(''))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt([]))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(true))
console.log(isInt(NaN))
console.log(isInt('1'))
console.log(isInt(function(){}))
console.log(isInt(Infinity))

console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))

Without checking type

If you don't care if the incoming type is actually boolean, string, etc. converted into a number, then just use the following:

function isInt(value) {
    try {
        BigInt(value)
        return true
    } catch(e) {
        return false
    }
}

function isInt(value) {
    try {
        BigInt(value)
        return true
    } catch(e) {
        return false
    }
}

console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(NaN))
console.log(isInt(function(){}))
console.log(isInt(Infinity))

console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
// gets converted to number
console.log(isInt(''))
console.log(isInt([]))
console.log(isInt(true))
console.log(isInt('1'))
ctwheels
  • 21,901
  • 9
  • 42
  • 77
2

Besides, Number.isInteger(). Maybe Number.isSafeInteger() is another option here by using the ES6-specified.

To polyfill Number.isSafeInteger(..) in pre-ES6 browsers:

Number.isSafeInteger = Number.isSafeInteger || function(num) {
    return typeof num === "number" && 
           isFinite(num) && 
           Math.floor(num) === num &&
           Math.abs( num ) <= Number.MAX_SAFE_INTEGER;
};
zangw
  • 43,869
  • 19
  • 177
  • 214
2

you can also try it this way

var data = 22;
if (Number.isInteger(data)) {
    console.log("integer");
 }else{
     console.log("not an integer");
 }

or

if (data === parseInt(data, 10)){
    console.log("integer");
}else{
    console.log("not an integer");
}
Adeojo Emmanuel IMM
  • 2,104
  • 1
  • 19
  • 28
2

The 'accepted' answer is wrong (as some comments below point out). this modification can make it work:

if (data.toString() === parseInt(data, 10).toString())
    alert("data is a valid integer")
else
    alert("data is not a valid integer")
formiaczek
  • 385
  • 3
  • 7
1

You can use regexp for this:

function isInteger(n) {
    return (typeof n == 'number' && /^-?\d+$/.test(n+''));
}
macloving
  • 1,227
  • 1
  • 18
  • 22
1
function isInteger(argument) { return argument == ~~argument; }

Usage:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // true<br>
isInteger("0.1"); // false<br>

or:

function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }

Usage:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // false<br>
isInteger("0.1"); // false<br>
Jahid
  • 21,542
  • 10
  • 90
  • 108
Martin Wantke
  • 4,287
  • 33
  • 21
  • 1
    interesting, only work for small integer,failed on big Int. isInteger(9000000000) returns false. the reason is bitwise operators treat numbers as if they were 32-bit signed integers. – anru Jun 22 '15 at 09:53
1

From http://www.toptal.com/javascript/interview-questions:

function isInteger(x) { return (x^0) === x; } 

Found it to be the best way to do this.

Avram Tudor
  • 1,468
  • 12
  • 18
  • 1
    not a correct implementation, only work for small integer, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger for correct implementation. – anru Jun 22 '15 at 10:04
1

This will solve one more scenario (121.), a dot at end

function isInt(value) {
        var ind = value.indexOf(".");
        if (ind > -1) { return false; }

        if (isNaN(value)) {
            return false;
        }

        var x = parseFloat(value);
        return (x | 0) === x;

    }
1

For positive integer values without separators:

return ( data !== '' && data === data.replace(/\D/, '') );

Tests 1. if not empty and 2. if value is equal to the result of a replace of a non-digit char in its value.

DanielL
  • 11
  • 2
1

Ok got minus, cause didn't describe my example, so more examples:):

I use regular expression and test method:

var isInteger = /^[0-9]\d*$/;

isInteger.test(123); //true
isInteger.test('123'); // true
isInteger.test('sdf'); //false
isInteger.test('123sdf'); //false

// If u want to avoid string value:
typeof testVal !== 'string' && isInteger.test(testValue);
Vasyl Gutnyk
  • 4,813
  • 2
  • 34
  • 37
0

I had to check if a variable (string or number) is an integer and I used this condition:

function isInt(a){
    return !isNaN(a) && parseInt(a) == parseFloat(a);
}

http://jsfiddle.net/e267369d/1/

Some of the other answers have a similar solution (rely on parseFloat combined with isNaN), but mine should be more straight forward and self explaining.


Edit: I found out that my method fails for strings containing comma (like "1,2") and I also realized that in my particular case I want the function to fail if a string is not a valid integer (should fail on any float, even 1.0). So here is my function Mk II:

function isInt(a){
    return !isNaN(a) && parseInt(a) == parseFloat(a) && (typeof a != 'string' || (a.indexOf('.') == -1 && a.indexOf(',') == -1));
}

http://jsfiddle.net/e267369d/3/

Of course in case you actually need the function to accept integer floats (1.0 stuff), you can always remove the dot condition a.indexOf('.') == -1.

jahu
  • 5,427
  • 3
  • 37
  • 64
0

Lodash https://lodash.com/docs#isInteger (since 4.0.0) has function to check if variable is an integer:

_.isInteger(3);
// → true

_.isInteger(Number.MIN_VALUE);
// → false

_.isInteger(Infinity);
// → false

_.isInteger('3');
// → false
Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70
0

After few successes and failures, I came up with this solution:

const isInt = (value) => {
  return String(parseInt(value, 10)) === String(value)
}

I liked the idea above of checking the value for not being NaN and use parseFloat, but when I tried it in React infrastructure it didn't work for some reason.

Edit: I found a nicer way without using strings:

var isInt = function (str) {
  return str === '0' || !!~~str;
}

I think it's the shortest answer. Maybe even the most efficient, but I could be stand corrected. :)

0

So many options in the answers.

isNaN can be tricky for pure integer and you still need other checks that make it obsolete.
Number.isInteger() isn't officially supported in IE (most wont care but there are stragglers out there).

I ended up writing something myself:

function isInteger(valueToCheck) {
    return typeof valueToCheck !== 'undefined'
        && (valueToCheck === parseInt(valueToCheck, 10));
}

Test

let undefinedValue;
const testValues = [
    1,
    '',
    undefinedValue,
    1.1,
    '1',
    '1.1',
    '1-2',
    'bob',
    false,
    [],
    [1],
    {},
    {foo: 1}
];

testValues.forEach(value => {
    console.log(`${value} - ${isInteger(value)}`);
})

Results:

1 - true
'' - false
undefined - false
1.1 - false
'1' - false
'1.1' - false
'1-2' - false
'bob' - false
false - false
[] - false
[1] - false
{} - false
{foo: 1} - false

Some test values are overkill but their existence just shows clearly nothing gets through. You could possibly omit the undefined check in the function, but I find undefined things can be weird in JS so felt more secure it being there.

James
  • 4,644
  • 5
  • 37
  • 48
0

With todays browsers Number.isInteger() is way to go just like many answers before this explained but I came across problem which is common and it ocured when I was building API.

So in API request, we receive properties as string, so Number.isInteger() will return false.

If we try checking it with Number.isInteger(parseInt()) then values like 1.1 or 1.asd will return true

To solve this problem I created function which checks if value is integer regarding it passed as integer or string

function isNumber(value) {
    return ([...value.toString()]
            .filter(x => [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ]
            .indexOf(x) >= 0))
            .length == Math.max(value.toString().length, 1)
}

Math.max() part is needed to handle empty strings

Aleksa Ristic
  • 2,394
  • 3
  • 23
  • 54
-1

Try the following function:

function isInteger (num) {
    return num == parseInt(+num,10)  && !isNaN(parseInt(num));
}

console.log ( isInteger(42));        // true
console.log ( isInteger("42"));      // true
console.log ( isInteger(4e2));       // true
console.log ( isInteger("4e2"));     // true
console.log ( isInteger(" 1 "));     // true
console.log ( isInteger(""));        // false
console.log ( isInteger("  "));      // false
console.log ( isInteger(42.1));      // false
console.log ( isInteger("1a"));      // false
console.log ( isInteger("4e2a"));    // false
console.log ( isInteger(null));      // false
console.log ( isInteger(undefined)); // false
console.log ( isInteger(NaN));       // false    
console.log ( isInteger(false));       // false
console.log ( isInteger(true));       // false
console.log ( isInteger(Infinity));       // false
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
-2

You can use regexp to do this:

function isInt(data){
  if(typeof(data)=='number'){
    var patt=/^[0-9e+]+$/;
    data=data+"";
    data=data.match(patt);
    if(data==null){return false;}
     else {return true;}}
  else{return false;} 
}

It will return false if data isn't an integer, true otherwise.

Jahid
  • 21,542
  • 10
  • 90
  • 108
  • 1
    That code will throw `TypeError: undefined is not a function`. `match` is a string method, you can't call it on a number, which `data` is. Even if you forced `data` to be a string, it still wouldn't always work because very large integers will give you exponent shorthand when converted to a string (e.g. `var data = 1000000000000000000000 + ""` will give you `"1e+21"` – Quentin May 27 '15 at 15:55
-2

Add class numOnly for the textbox,

$(document).on("input", ".numOnly", function(e) {
    this.value = this.value.replace(/[^0-9\$]/g,'');
    if(this.value!=""){
      alert('Integer Number.');
    }else{
      alert('Not an Integer Number.');
   }
});

It works for me.. Try this one

You can use keypres,keyup,keydown etc., instead input.

Prabhagaran
  • 3,620
  • 1
  • 19
  • 19