How to round a Floating Number (Number with decimals) to a specific decimal place

So, How to round a Floating Number to a decimal place?

Before you found this post, if you are already confused with the problem, I guess that you may have already asked the Assistant, which is a AI chatbot that tells you everything about game development, although the bot sucks :skull:, and I think that it will not tell you the answer because even itself dosen’t know.

Now, to do that, we are gonna use string.format(), here’s a piece of example code :

local num = 1.546 -- This is our Floating Number
local formatted_num = string.format("%.1f", num) 
-- The "1" inside "%.1f" represents the decimal place your want your number to round to. "1" equals to the first decimal place.

It should print out this as expected :

1.5 -- 1.546 is equal to 1.5 after rounding to one decimal place

Now if we change the number inside "%.1f" in the above code to 2, this will be printed out :

1.55 -- 1.546 is equal to 1.55 after rounding to two decimal places

Well, I hope this was useful to you!

1 Like