Here is an example: 3 would round to 2 or 5 will round to 6. How would you do it exactly?
This function rounds any number n
to the nearest number to
function round( n, to )
return math.floor(n/to + 0.5) * to
end
So to round to the nearest even number, you just round to the nearest 2.
E.g. round(4.9, 2)
returns 4
So if I do something complex, lets say:
round(-79, 2)
It will return either -80, or -78? (I don’t think that is right )
I assume you know about math.floor() right?
It rounds any number down. 4.5 → 4. At first you might think, no that’s what I’m looking for. But now think what happens when you add +0.5 to it?
4.5+0.5 = 5 round 5 down and you get, 5! 4.4+0.5 = 4.9, down that down and you get 4. Now this rounds down to simple numbers. Still not exactly what you want. What if you devide and then multiply? 4/3=1.333 multiply that by 3 and you get 4 again. Now this is useless unless, you guessed it. Round it.
By using the formula:
math.floor(x/y+0.5)*y
you get an rounded number back.
Let’s say x = 5 and you want to round that by 3. You would do
math.floor(5/3+0.5)*3
which returns 6. If x was 4 it would return 3 etc.
In code form:
functon roundTo(x,y)
return math.floor(x/y+.5)*y
end
I am confused what you mean by rounding. Do you mean rounding of doubles or rounding of two values of fixed numbers?
math.floor()
, math.ceil()
are options for now.
If I had an odd number then round down , then it will be even. How can I achieve this?
Hmm which post should I mark as a solution?
Try this:
number = math.floor(number - (number % 2)) -- lol
local function round_to_even(num: number): number
return math.floor(num - num%2)
end
a i got beat
It works exactly how you want it to. If an odd number is provided (e.g. 27), it rounds down, in this case 26.
28 → 28
27 → 26
30.4 → 30
etc
If you want to round down at odd numbers instead of up, then math.ceil(n/2 - .5)*2
will achieve that. If you don’t want to round to the “nearest” even number and instead only want to round down to the greatest even number less than or equal to n
then n - n%2
will achieve that.