How to know if the calculation generated an integer?

Asked

Viewed 1,101 times

5

How to know if the calculation generated an integer ?

example: if (10 / 2 = NUMERO INTEIRO) {}

2 answers

9

Another alternative to Pope Charlie’s correct answer is to see if the rest of the division by 1 is zero.

Using the operator %, and if the number is integer, then divide by 1 should give zero rest.

if ((10 / 2) % 1 == 0) { } // eu sou inteiro!
else { } // eu não sou inteiro!

If you use this feature several times you can do a function for this, for example:

function inteiro(nr) {
    return nr % 1 == 0;
}
console.log(inteiro(10/2)); // true
console.log(inteiro(10/3)); // false
console.log(inteiro(10/4)); // false
console.log(inteiro(10/5)); // true

jsFiddle: http://jsfiddle.net/Sergio_fiddle/g45n0hek/

8


parseint (reference)

divisao = 10/2;
if( divisao === parseInt( divisao ) )
{    
    alert("10/2 resultou em inteiro")
}
else
{
    alert("10/2 não é um inteiro")
}

Browser other questions tagged

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