Modulus
Well, the easiest way of doing this would be using the modulus operator, which essentially gets the remainder of quotient of the number before it and the number after it.
For example:
9%4
would return 1 as 4 goes into 9 twice, 4*2 = 8, and 9-8 is 1
An example of this would be:
function RoundToNumber (num,roundNum)
if num%roundNum >= roundNum/2 then
return num - num%roundNum + roundNum
else
return num - num%roundNum
end
end
this would round to the nearest provided roundNum.
It essentially rounds up if the remainder of quotient of the number and the number you want to round to is greater than half of the number you want to round to.
Visualizing with numbers
By adapting a more general function like that, we can get this result:
function RoundTo3 (num)
if num%3 >= 3/2 then
return num - num%3 + 3
else
return num - num%3
end
end
Hopefully now you can visualize it more clearly.
The reason that we use modulo here is that it lets us get to a number between 0 and 3, which then can help us deduce whether it is closer to the upper multiple of 3, (result >=1.5), or the lower multiple of 3 (result < 1.5)
An example of this function would be:
RoundTo3(67)
as 67%3 is 1 (as the multiple of 3 below it is 66), it rounds down to 66:
so: the function returns 67 - 67%3, or 67 -1, which is 66
Another example would be:
RoundTo3(23)
as 23%3 is 2 (as the multiple of 3 below it is 21), it rounds up to 24:
so: the function returns 23 - 23%3 + 3 = 23 - 2 + 3 = 21 + 3 which is 24
Hopefully this helped, be sure to accept if it did!
5 comments
Do you mean like round up to the nearest whole number?
Please edit your question to be more specific about what you actually mean. Your examples aren't really clear as to what you're looking for.
Are you sure you know what you're talking about? When rounded, 58 never becomes 57. It doesn't matter what kind of rounding you're doing.
I see what you mean now, but rounding isn't the correct terminology.
Let me edit my answer.