How can I get math.floor/math.celi to round too the nearest 5?
Divide it by 5, apply math.floor/math.ceil, and multiply it by back by 5.
Floor:
function floor5(n) return (math.floor(n/5)*5) end
output:
> print(floor5(-4.99)) -5 > print(floor5(-5.01)) -10 > print(floor5(4.99)) 0 > print(floor5(5.01)) 5
Ceiling:
function ceil5(n) return (math.ceil(n/5)*5) end
Output:
> print(ceil5(-4.99)) -0 > print(ceil5(-5.01)) -5 > print(ceil5(4.99)) 5 > print(ceil5(5.01)) 10
For a function that rounds to the nearest 5, apply one of these methods to the quotient (I'm using method #5):
function round5(n) return (math.floor(n/5 + 1/2)*5) end
Output:
> print(round5(7)) 5 > print(round5(8)) 10 > print(round5(7.5)) -- 1.5 after division, so it gets round up. 10
EDIT: You can generalize this (e.g. rounding to the nearest 2, 0.1, etc.) by replacing 5
with something else:
function round(n, multiple) return (math.floor(n/multiple + 1/2) * multiple) end
Output:
> print(floor(3.34, 2)) -- 3.34 is 1.34 away from 2 and 0.66 away from 4 in the number line 4 > print(floor(3.34, 1)) -- 3.34 is 0.34 away from 3 and 0.66 away from 4 3 > print(floor(3.34, .2)) -- 3.34 is 0.14 away from 3.3 and 0.06 away from 3.4 3.4 > print(floor(3.34, .1)) -- 3.34 is 0.04 away from 3.3 and 0.06 away from 3.4 3.3
You can round to a whole number by using math.floor(x +0.5)
. You'll get numbers like 1, 2, 3, 4 out of this, but you want numbers like 5, 10, 15, 20. To make this round to the nearest multiple of 5, you need to know how to make sequence 2 match sequence 1, and then reverse what you did after the rounding.
Let's try this with another sequence first, like 0.5, 2.5, 4.5, 6.5. We can tell that they are increasing by 2 each time, so let's compare it to 2's multiples, 2, 4, 6, 8. Now we know that they are 1.5 less than multiples of 2. math.floor((x+1.5)/2 +0.5)*2-1.5
Since you are just using multiples of 5 this is very easy. math.floor(x/5 +0.5)*5