28

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.
  • 171,639
  • 30
  • 264
  • 288
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 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

7 Answers7

51

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;
}
Kols
  • 3,641
  • 2
  • 34
  • 42
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
34

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

Evren Kuzucuoglu
  • 3,781
  • 28
  • 51
12

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

( x + y - 1 ) / y
Milan Matějka
  • 2,654
  • 1
  • 21
  • 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,374
  • 1
  • 17
  • 18
3

+0.5 will aways round to the higher.

Atanas Atanasov
  • 203
  • 1
  • 4
1

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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Shubham agarwal
  • 157
  • 2
  • 3
  • 14
  • 1
    [ceil()](https://learn.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://learn.microsoft.com/en-us/dotnet/api/system.math.ceiling?view=netframework-4.8) – mins Aug 24 '19 at 10:56
0

It's better to use MidpointRounding from Math.Round

In your case:

Math.Round(value, MidpointRounding.AwayFromZero);

see more: https://learn.microsoft.com/ru-ru/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-double-system-midpointrounding)

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103