tags:

views:

1413

answers:

3

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 nearest multiple of 20, it should return 100.

Is there a method built-in method in the .NET framework I can use for this?

The reason I'm asking for a built-in method is because there's a good chance it's been optimized already.

+5  A: 

Yes, integer arithmetic.

To round m up to the next multiple of n, use ((m+n-1)/n)*n

Joe
As long as n != 0 of course.
Jason Lepack
Also, the "next multiple" of a negative number is actually rounding down.
Jason Lepack
True enough, but the OP needs to do some of the work :)
Joe
I agree :D, just saying.. ;)
Jason Lepack
You seemed to have missed the part where I asked for a "built-in" method.
ilitirit
+2  A: 
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
*/
Jason Lepack
+1  A: 

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.