24

I need to find a division of two integers and round it to next upper integer

e.g x=7/y=5 = 2; here x and y always greater than 0

This is my current code

 int roundValue = x % y > 0? x / y + 1: x / y;

Is there any better way to do this?

Alex K.
  • 165,803
  • 30
  • 257
  • 277
Damith
  • 60,955
  • 13
  • 99
  • 152
  • Duplicate? http://stackoverflow.com/questions/921180/how-can-i-ensure-that-a-division-of-integers-is-always-rounded-up/926806 – chrisaut Aug 01 '11 at 11:12

6 Answers6

49

You could use Math.Ceiling... but that will require converting to/from double values.

Another alternative is to use Math.DivRem to do both parts at the same time.

public static int DivideRoundingUp(int x, int y)
{
    // TODO: Define behaviour for negative numbers
    int remainder;
    int quotient = Math.DivRem(x, y, out remainder);
    return remainder == 0 ? quotient : quotient + 1;
}
Kolappan N
  • 2,875
  • 2
  • 31
  • 38
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
29

Try (int)Math.Ceiling(((double)x) / y)

Evren Kuzucuoglu
  • 3,603
  • 26
  • 50
12

All solutions looks too hard. For upper value of x/y, use this one

( x + y - 1 ) / y
Milan Matějka
  • 2,574
  • 1
  • 18
  • 23
  • 'add another group, but subtract one in case you already had a full group' - great idea. seems there's no problem so long as ints are positive. thanks for sharing! – jacoblambert Jun 03 '16 at 12:24
4

dunno what's better way or how to define a better way (if in terms of performance you have to run tests to see which will be faster), but here's my solution:

int roundValue = x / y + Convert.ToInt32(x%y>0);

p.s.

still have to deal somehow with neg. numbers... IMO this is the simplest.

Nika G.
  • 2,284
  • 1
  • 17
  • 18
2

+0.5 will aways round to the higher.

0

Use ceil() function. It gives the upper value.

Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
Shubham agarwal
  • 147
  • 2
  • 3
  • 14
  • [ceil()](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/ceil-ceilf-ceill?view=vs-2019) is part of C++. Equivalent for C# is [Math.Ceiling()](https://docs.microsoft.com/en-us/dotnet/api/system.math.ceiling?view=netframework-4.8) – mins Aug 24 '19 at 10:56