I\'m looking for a method that can round a number up to the nearest multiple of another. This is similar Quantization.
Eg. If I want to round 81 up to the
public static int RoundUp(int num, int multiple)
{
if (multiple == 0)
return 0;
int add = multiple / Math.Abs(multiple);
return ((num + multiple - add) / multiple)*multiple;
}
static void Main()
{
Console.WriteLine(RoundUp(5, -2));
Console.WriteLine(RoundUp(5, 2));
}
/* Output
* 4
* 6
*/
If you're using a lot of these on a relatively slow platform, you may eliminate the multiplication by using a variant of:
t = m + n - 1; return (t - (t % n));
Of course, if you can limit your multiple to values of 2^n, then the modulus operation may also be deprecated in favour of its logical equivalent (usually "&").
Incidentally, the "RoundUp" function illustrated above is seriously flawed and will only round down correctly when {(m % n) == (n - 1)}; rounding down is implicit for integer division and as such, does not require compensation.
Lee's answer is good but it should have been:
t = m + n - 1; return (t - (t % m));
Notice the change from N
to M
. The modulo operation should be done with the multiplier (m)
and not with the number (n)
.
Yes, integer arithmetic.
To round m up to the next multiple of n, use ((m+n-1)/n)*n