- Home /
Checking for divisible by 2
In JavaScript how do I check to see if an int is divisible by 2?
Jason
Answer by YoungDeveloper · Oct 13, 2013 at 10:06 PM
if( someNumber % 2 == 0){
}
Just to elaborate on this - the % symbol is the modulus sign. When given two numbers, like this: a % b
, it finds the remainder when a is divided by b. When this remainder is 0, then a is divisible by b. For example, 5%2
gives 1 (since 5/2 is 2 remainder 1), while 6%2
is 0 (since 6/2 is 3 with no remainder).
Some more examples:
31% 10 = 1
7 % 3 = 1
10 % 5 = 0
12 % 7 = 5
Answer by Eric5h5 · Oct 15, 2013 at 04:59 AM
A little faster than using modulus:
if (foo & 1) {
// odd
}
else {
// even
}
It will also always result in 1 for odd numbers regardless if the input is positive or negative, whereas modulus will return -1 for negative odd numbers. It only works for integers though, not floats.
Your answer
Follow this Question
Related Questions
Help! How to check letter spelling automatically after drag and drop 0 Answers
Easy way to check if DirectX is used as renderer (instead of Open GL or Open GL ES) 1 Answer
Boolean Uncheck Inspector if False 2 Answers
Check if Gamepad is Plugged in 1 Answer
Check for closed circuit of pickups 2 Answers