Best way to round a number to the nearest 10

Quick question

What’s the most efficient way to round a number to the nearest 10?

For example

25 —> 30

41 —> 40

3 Likes
function round10(num)
	return math.floor(num / 10 + 0.5) * 10
end
8 Likes

That seems pretty calculation heavy, is there any more efficient solution?

I was about to suggest the same; there isn’t a better solution afaik.

I believe that is the best-known method of rounding in most languages. Multiplication and division have slightly higher runtime complexity than addition but it wouldn’t be big enough to significantly affect your game’s performance.

1 Like

Yes, there is. If you’re willing to have it round down:

local function down(x, n) 
	-- x is the number to round, n is what it rounds to the nearest multiple of (so 10)
	return x - x % (n or 1)
end

Otherwise:

local function down(x,n)
	local x = x + (0.5 * n)
	return x - x % (n or 1)
end

This avoids the function overhead of calling math.floor.

Keep in mind the difference is negligible, so you should do whichever solution you think is cleaner. Here’s a benchmark that does ten million repetitions of each function:
image
… and this modulo-based function only beats it by .007 seconds. Really irrelevant in the long run.


Edit: After hard-coding the fact it’s rounded to the nearest tenth, you see a slightly larger gap, but it could just be noise.

hardcoded to the nearest tenth
function(x)
	x = x + 5
	return x - x % 10
end

image

Still not even a hundredth of a second, though, (unless I cherrypick the benchmarks :wink:):
image

8 Likes

Can’t be wasting those milliseconds :stuck_out_tongue:

1 Like