We often come across the recurring floating-point fault.
Ex: print(1.1 + 1.8) -- 2.9000000000000004
To fix this. we resort to math.round
. However, this function only rounds to integers.
So I created this function that makes rounding easier.
Optionally, you can provide a third parameter if you want to do “large” rounding to multiples of a specific number.
-- Round floating-point numbers, with given digits and optional multiples
function Round(Number, Digits, Multiples)
local Num = math.round(Number * 10^Digits) / 10^Digits
if Multiples then Num = math.round(Num / Multiples) * Multiples end
return Num
end
Ex:
-- to round numbers to 1 decimal place
print(Round(-7.04, 1)) -- -7
print(Round(-7.05, 1)) -- -7.1
-- (to round angles every 90 degrees)
print(Round(44, 1, 90)) -- 0
print(Round(45, 1, 90)) -- 90