How do I round a decimal to a specific number of decimal places?

For example, I got a ridiculously long decimal like:

0.01943638963

I tried math.floor but that gives me:

0

or math.ceil which gives:

1

OR math.round:

0

so how do I round a decimal to a specific number of decimal places?

1 Like

You could do something like this:

local function Round(x, mult)
	return math.round(x / mult) * mult
end

It will round to the nearest mult number (kinda misnamed variable). For instance, to round in 0.01 increments:

print(Round(0.0194363, 0.01)) --> 0.02

You can use this to round to larger numbers too:

print(Round(152, 50)) --> 150
7 Likes

Thank you so much, it worked. Have a nice day! :happy1:

local num = 3.1415926535
local roundedNum = string.format("%.3f", num)
print(roundedNum)  -- Output: 3.142
2 Likes

I made a function with this and worked perfectly, no more of 0.1231412412 in my Guis thanks! function:

local function round(num)
--change "%.2f" to the number of decimals you want to get for example: 
--"%.2f" = 0.12 , "%.3f" = 0.123, %.4f = 0.1234.
	local roundedNum = string.format("%.2f", num)
	return roundedNum
end

--Calling the function
round(51.8745)
--output would be 51.87 since we using "%.2f"
3 Likes