I was wondering, how can I check if a number isn't whole, or contains a decimal or fraction. How can I do this?
A whole number modulo 1 is 0:
if num % 1 == 0 then -- Whole number else -- Not whole end
Modulo is remainder after division.
If x mod y
(Lua use %
as an operator) is congruent to u
if u + ky = x
for an integral k
and 0 < u < y
. E.g., 2.1 mod 0.5
is 0.1
since it's .1
more than .5 * 4
.
We could also compare the number to its own floor
. The floor of 2
is 2
; the floor of 3.01
is 3
.
if math.floor(num) == num then -- Whole else -- Not whole end
(If we define floor
as x - (x % 1)
then we see this is equivalent to the first)
Another option, though a bad one, is to use the string representation of the number (this is complicated Lua using exponential notation on larger numbers)