Simple Round function with digits and optional multiples

We often come across the recurring floating-point fault.
Ex: print(1.1 + 1.8) -- 2.9000000000000004
To fix this. we resort to math.round. However, this function only rounds to integers.
So I created this function that makes rounding easier.
Optionally, you can provide a third parameter if you want to do “large” rounding to multiples of a specific number.

-- Round floating-point numbers, with given digits and optional multiples
function Round(Number, Digits, Multiples)
	local Num = math.round(Number * 10^Digits) / 10^Digits
	if Multiples then Num = math.round(Num / Multiples) * Multiples end
	return Num


-- to round numbers to 1 decimal place
	print(Round(-7.04, 1)) -- -7
	print(Round(-7.05, 1)) -- -7.1

-- (to round angles every 90 degrees)
	print(Round(44, 1, 90)) -- 0
	print(Round(45, 1, 90)) -- 90


You put it in #resources:community-tutorials ,
which means it is supposed to be a detailed tutorial.

Not for me, but for others - maybe add some details and more info on how that function works and the calculations you did there?

Overall, it’s pretty good.


This has some more cool examples in depth.


This seems like something that should be in the community resources category instead, but it’s still a useful function; I’m using it if I display a floating point number to keep the decimal places limited.

1 Like