Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I detect if a number is odd or even?

I've made a terrain system to generate blocks of terrain. To do this, it cuts certain vectors in half. But since it's a module script, if someone else put in an odd number, it would have a decimal number, which crashes the terrain system. So how do I detect an odd number so I can fix it?

2 answers

✓ Accepted answer

We can use the modulus "operator" % to determine the remainder after division of a number.

If x is even, then x % 2 is 0 since 2 goes evenly into an even number.


5 / 2 is 2 with a remainder of 1. 5 % 2 is that remainder (1)


Examples:

1 % 3 is 1

2 % 3 is 2

3 % 3 is 0

4 % 3 is 1

5 % 3 is 2

6 % 3 is 0

7 % 3 is 1

8 % 3 is 2

9 % 3 is 0

10 % 3 is 1


It even works with fractions:

1 % 1.5 is 1

1.5 % 1.5 is 0

2 % 1.5 is 0.5

2.5 % 1.5 is 1

3 % 1.5 is 0

3.5 % 1.5 is 0.5

4 % 1.5 is 1


A warning about the sign (positive / negative) of the result:

The sign of a % b matches the sign of b (in Lua). So:

  • 5 % (-2) is -1
  • (-5) % (-2) is -1
  • (-5) % 2 is 1

1 comment

0

Thanks a ton!

Simply use a modulo (%). It's used to find the remainder when dividing by something. When dividing by 2, if the remainder is 0, the number is even. Otherwise, it's odd.

if (number%2) == 0 then
--number is even
else
--number is odd
end

2 comments

2

BlueTaslem keeps beating me to questions.

1

:)

This discussion is preserved as it was. New answers, comments, and votes are closed.