How to round numbers (SOLVED)


#1

I have a GUI that shows the value of os.clock + 87, but the numbers are really specific, but I really only need a timer that goes to tenths/hundredths or larger. Is there a way to round the numbers?


#2

Use math.ceil or math.floor :slight_smile: . Although, those only round up or down. To get it to round the way we normally do, I found this. I didn’t test it, but it was selected as the best answer:

function round(n)
    return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
end

#3

That will round to the nearest integer. I think @klu2022 wants to retain decimals, but limit them to tenths or hundreds when showing the number in a gui.

For that I’d use string.format():

print(string.format("Time: %.2f", 12.34567))  -- 12.35

#4

Okay that works, where can I find what the different letters at the beginning do? (%.2f)


#5

You can find it our copy of the Lua docs, or online