Is there a way to detect whether a number is a whole number or not? Like if a number is 2.6873, then it will be false
, but if it is 2 or 10, then it will be true
. Is there a way I can achieve this?
You can use the modulo operation for that:
if number % 1 == 0 then
print(number, "is a whole number")
else
print(number, "has a decimal part")
end
Modulo returns the remainder of dividing the left side by the right side.
Edit: These are more logical ways to check for “wholeness,” but the top one is the shortest.
math.round(number) == number
math.floor(number) == number
math.ceil(number) == number
2 Likes
Is it normal for it to print 5 times?
It should only print once if it’s by itself. If this code is in a loop or event binding, it might print more than once.