Rounding in Lua

Hi i’m using LÖVE2D with the Zerobrane Studio IDE. I’ve managed to get the first two answers which you can see down below:
{
number = 6.283

print(math.floor(number))
print(math.ceil(number))

Output:
6
7
}

But i don’t know how to do the last two exercises and i can’t find any helpful information on the net. Does anybody know how to round to 1 and 2 decimal places in Lua?

Hi @fabianspar. I’m not overly familiar with the language but, as far as I recall, there is no built in rounding functions in lua.

One hacky solution would be to use string formatting to get the job done. Something along the lines of string.format("%.1f", n) and string.format("%.2f", n).
However, I’m not sure if that will round the value in lua, or truncate it.

The other option would be to write a custom function that does the job properly, where you could also specify the type of midpoint rounding you want to use.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms