Make a function that shows whether the number is integer or not

2

I need to do a function that returns: it is integer or not integer.

    
asked by anonymous 13.03.2018 / 02:13

3 answers

2

Using parseInt with radix 10 (decimal):

function isInt(n){
   return n === parseInt(n, 10);
}

console.log( isInt(1) ); // retorna true
console.log( isInt(1.5) ); // retorna false
console.log( isInt(1.0) ); // retorna true
console.log( isInt(10/5) ); // retorna true
console.log( isInt(10/4) ); // retorna false

Note that the === operator will check whether the value is equal to the value and type.

If the type is indifferent (number or string), you can use == :

function isInt(n){
   return n == parseInt(n, 10);
}

// strings
console.log( isInt('1') ); // retorna true
console.log( isInt('1.5') ); // retorna false
console.log( isInt('1.0') ); // retorna true

// números
console.log( isInt(1) ); // retorna true
console.log( isInt(1.5) ); // retorna false
console.log( isInt(1.0) ); // retorna true
  

Note that the Number.isInteger method is not supported on the Internet   Explorer.

    
13.03.2018 / 02:24
7

Basically use Number.isInteger , example:

// Returns true
console.log(Number.isInteger(100));
console.log(Number.isInteger(-100));

// Returns false
console.log(Number.isInteger(Number.NaN));
console.log(Number.isInteger(Infinity));
console.log(Number.isInteger(100 / 3));
console.log(Number.isInteger("100"));

Reference: Number.isInteger (Number) (JavaScript) function

    
13.03.2018 / 02:20
0

The best solution would be (compatible with all browsers)

function isInteger(numero) {
  return (numero ^ 0) === numero && typeof(numero) == "number";
}

Example:

 isInteger(2)
 true
 isInteger(1.5)
 false
    
13.03.2018 / 10:00