 What do you think about this function which rounds to the nearest integer? I made this myself and it certainly does work, and I’m very proud of it because I made it without any outside help. Do you have any criticisms or any optimizations that may be used to make this a better function?

``````function round(num)
if num%math.floor(num) >= 0.5 then
return math.ceil(num)
else
return math.floor(num)
end
end
``````

Essentially what it does is take a number (preferably with a decimal) and modulates the floor of itself. For example,
INPUT => 18.3

1. You want to round 18.3
2. 18.3 goes into the function and the modulus of 18(which is 18.3 rounded down) gives you the number 0.3
3. Is 0.3 greater than or equal to 0.5? No.
4. No? Round down.
OUTPUT => 18
2 Likes

It’s good,but it can be better. Something like this will work:

``````function round(x)
return math.floor(x + 0.5)
end
``````

How it works:
Say we have a number 8.4. In the function, it will add 0.5 to it, giving 8.9. The floor function will round down to produce 8. If we have 8.7, the function will add 0.5, giving 9.2, the floor function will round down, producing 9

6 Likes

I don’t see why you are using floor(num) there as your modulus - I think you may have a misunderstanding of what modulo (%) does (in Lua at least). You should simply be using ‘1’ as your modulus (the number after the %). There are two reasons for this:

1. For positive numbers, this achieves the same result as what you are currently doing, except this way you don’t make a redundant `math.floor` function call.

2. For negative numbers, your method does not produce the results you might expect from a rounding function. For example, your function rounds -18.3 to -19, but I think it is probably more reasonable that it should round it to -18. Using a modulus of 1 will solve this.

``````-- normal method
local function round(n)
return math.floor(n + 0.5)
end

local function round(n)
if n % 1 >= 0.5 then
return math.ceil(n)
else
return math.floor(n)
end
end

-- another version using modulo
local function round(n)
return (n + 0.5) - (n + 0.5) % 1
end
``````
6 Likes