Rounding a number to the nearest 0.5

How would I round a number to the nearest 0.5? I’m not that good at the math stuff so help will be appreciated :happy1:

1 Like

Heres a quick module I made for rounding numbers!

local roundingFunction = {}

function roundingFunction.round(number, increment)
    	if number % increment < increment / 2 then
		return number - (number % increment)
	else
		return (number + increment) - (number % increment)
	end
end

return roundingFunction 

Hope it helps :wink:

Update:

A more simpler method:

local roundingFunction = {}

function roundingFunction.round(number, increment)
	return math.round(number*(1/increment))/(1/increment)
end

return roundingFunction 

Both works and I don’t know which one goes faster, but recommends the 2nd one

1 Like

Or you could just do:

math.floor(number) + 0.5
1 Like

Not quite what they are asking. They would want it to round to values such as 1.0, 1.5, 2, 2.5 ect
Your script would round to 0.5, 1.5, 2.5

3 Likes

Pretty sure

local rounded = math.round(n*2)/2

will work for your case:

4 Likes