I need to do a function that returns: it is integer or not integer.
I need to do a function that returns: it is integer or not integer.
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.
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"));
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