86

How can I check if a variable is currently an integer type? I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)

asked Dec 22, 2010 at 23:18
2
  • 9
    == checks for value equality, === checks for value and type equality. "1" == 1 would be true, "1" === 1 would be false Commented Dec 22, 2010 at 23:22
  • you can consider using a very small library like Not. Solves all problems. Commented Jun 2, 2020 at 19:02

8 Answers 8

135

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10)
answered Dec 22, 2010 at 23:21
Sign up to request clarification or add additional context in comments.

9 Comments

you can also use isNaN(foo) w3schools.com/jsref/jsref_NaN.asp instead of typeof
"it doesn't distinguish between different types of Number" That's because there are no different types of Number. All numeric values in JS are 64-bit floats.
@NullUserException — That's what I said.
If you're using jQuery, you can use it's $.type() function. Ex. $.type("1") # => "string"
This answer should be updated as it's inconsistent with the ECMAScript 2015 Number.isInteger function. It should return false for Infinity, not true.
|
21

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false
answered Aug 16, 2015 at 17:14

Comments

7

A number is an integer if its modulo %1 is 0-

function isInt(n){
 return (typeof n== 'number' && n%1== 0);
}

This is only as good as javascript gets- say +- ten to the 15th.

isInt(Math.pow(2,50)+.1) returns true, as does Math.pow(2,50)+.1 == Math.pow(2,50)

Liam
30k28 gold badges145 silver badges206 bronze badges
answered Dec 23, 2010 at 3:43

Comments

2

A clean approach

You can consider using a very small, dependency-free library like Issable. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error
// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')
define({
 primitives: 'number',
 nameOfTyping: 'integer',
 toPass: function(candidate) {
 // pre-ECMA6
 return candidate.toFixed(0) === candidate.toString()
 // ECMA6
 return Number.isInteger(candidate)
 }
})
is(4.4).custom('integer') // throws error
is(8).custom('integer') // returns true

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
 // any of these below will throw errors to protect you
 is(string).string()
 is(boolean).boolean()
 // continue with your code.
}
answered Jun 2, 2020 at 19:07

2 Comments

could you please explain how to check if something is an integer using this technique?
@sova i have added the example.
1

I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.

function isFloat( x )
{
 return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
}

Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0's) as an INTEGER. It actually needs a floating point precision error to occur to detect the floating point values in that case.

Ex.

alert(isFloat(5.2)); //returns true
alert(isFloat(5)); //returns false
alert(isFloat(5.0)); //return could be either true or false
answered Oct 23, 2013 at 17:56

Comments

1

You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:

Strict compare of different types: 123 (number) === "123" (string)

answered Apr 1, 2017 at 8:02

Comments

0

Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:

function isInt(x) {
 return typeOf(x, 'Number') && x % 1 == 0;
}

The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2

answered Nov 22, 2015 at 22:36

Comments

0

Try this code:

 alert(typeof(1) == "number");
Liam
30k28 gold badges145 silver badges206 bronze badges
answered Dec 22, 2010 at 23:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.