Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET method to round a number up to the nearest multiple of another number?

Tags:

.net

rounding

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.

like image 271
ilitirit Avatar asked Dec 19 '08 13:12

ilitirit


1 Answers

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
*/
like image 190
LeppyR64 Avatar answered Nov 07 '22 00:11

LeppyR64