Lua: Rounding numbers and then truncate

Ralph picture Ralph · Aug 19, 2013 · Viewed 74.7k times · Source

Which is the best efficient way to round up a number and then truncate it (remove decimal places after rounding up)?

for example if decimal is above 0.5 (that is, 0.6, 0.7, and so on), I want to round up and then truncate (case 1). Otherwise, I would like to truncate (case 2)

for example:
232.98266601563 => after rounding and truncate = 233 (case 1)
232.49445450000 => after rounding and truncate = 232 (case 2)
232.50000000000 => after rounding and truncate = 232 (case 2)

Answer

Ola M picture Ola M · Aug 19, 2013

There is no build-in math.round() function in Lua, but you can do the following: print(math.floor(a+0.5)).