Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Check variable is an integer or not in Javascript

In this chapter, you will learn about how to check variable is an integer or not in Javascript., here I am listing the possible ways to check if the value is an integer or not.

Solution 1:
Number.isInteger(): To check if the variable is an integer or not, use the method Number.isInteger(), which determines whether the passed value is an integer. Let’s write an example of the same.

let num = 500;
let checkIfInteger = Number.isInteger(num);
console.log(checkIfInteger);

if(Number.isInteger(num)) {
  console.log('Variable num is integer');
} else {
  console.log('Variable num is not a integer');
}

// Output
// true
// Variable num is integer

Let’s check for non-integer,

let num = 500.50;
let checkIfInteger = Number.isInteger(num);
console.log(checkIfInteger);

if(Number.isInteger(num)) {
  console.log('Variable num is integer');
} else {
  console.log('Variable num is not a integer');
}

// Output
// false
// Variable num is not a integer

Solution 2:
parseInt(): We can also use the function parseInt() to check if the value is an integer or not, it parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). Let’s write an example of the same.

let num = 500;

if (num === parseInt(num, 10))
    console.log("Variable num is an integer")
else
    console.log("Variable num is not a integer")

// Output
// Variable num is an integer

Let’s check for non-integer,

let num = 500.90;

if (num === parseInt(num, 10))
    console.log("Variable num is an integer")
else
    console.log("Variable num is not a integer")

// Output
// Variable num is not a integer

Solution 3:
We can also use the regular expression,

const checkIfInteger = (num) => {
  var regExp = /^-?[0-9]+$/;
    return regExp.test(num);  
}

let num = 500;

if (checkIfInteger(num))
    console.log("Variable num is an integer")
else
    console.log("Variable num is not a integer")

// Output
// Variable num is an integer

Let’s check for non-integer,

const checkIfInteger = (num) => {
  var regExp = /^-?[0-9]+$/;
    return regExp.test(num);  
}

let num = 500.60;

if (checkIfInteger(num))
    console.log("Variable num is an integer")
else
    console.log("Variable num is not a integer")

// Output
// Variable num is not a integer

Solution 4:
We can also use the typeof operator to check whether the value is an integer or not, let’s write an example

const checkIfInteger = (num) => { 
  return (typeof num === 'number') && (num % 1 === 0); 
}

let num = 500;

if (checkIfInteger(num))
    console.log("Variable num is an integer")
else
    console.log("Variable num is not a integer")

// Output
// Variable num is an integer