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

Asked

Viewed 94 times

2

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

  • 1

    you’ve tried to do something?

  • As a matter of fact, I have no logic in mind.

3 answers

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: Function Number.isInteger (Number) (Javascript)

2


Pose to use 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 if the value is equal in 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 method Number.isInteger is not supported on the Internet Explorer.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.