251

I want to ensure that a division of integers is always rounded up if necessary. Is there a better way than this? There is a lot of casting going on. :-)

(int)Math.Ceiling((double)myInt1 / myInt2)
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Karsten
  • 8,015
  • 8
  • 48
  • 83
  • 48
    Can you more clearly define what you consider "better"? Faster? Shorter? More accurate? More robust? More obviously correct? – Eric Lippert May 28 '09 at 16:40
  • 6
    You always have lots of casting with maths in C# - that's why it's not a great language for this sort of thing. Do you want the values rounded up or away from zero - should -3.1 go to -3 (up) or -4 (away from zero) – Keith May 29 '09 at 10:43
  • 9
    Eric: What do you mean by "More accurate? More robust? More obviously correct?" Actually what I did mean was just "better", I would let the reader put meaning into better. So if someone had a shorter piece of code, great, if another one had a faster, also great :-) What about you do you have any suggestions? – Karsten May 29 '09 at 20:13
  • 1
    possible duplicate of [How to Round Up The Result Of Integer Division](http://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division) – Ian Nelson Nov 13 '10 at 22:51
  • 7
    It's really amazing how subtly difficult this question turned out to be, and how instructive the discussion has been. – Justin Morgan - On strike Jan 13 '11 at 18:05
  • I must agree with Justin. This is why Peer Review exists. – surfasb Jun 15 '11 at 15:48

10 Answers10

682

UPDATE: This question was the subject of my blog in January 2013. Thanks for the great question!


Getting integer arithmetic correct is hard. As has been demonstrated amply thus far, the moment you try to do a "clever" trick, odds are good that you've made a mistake. And when a flaw is found, changing the code to fix the flaw without considering whether the fix breaks something else is not a good problem-solving technique. So far we've had I think five different incorrect integer arithmetic solutions to this completely not-particularly-difficult problem posted.

The right way to approach integer arithmetic problems -- that is, the way that increases the likelihood of getting the answer right the first time - is to approach the problem carefully, solve it one step at a time, and use good engineering principles in doing so.

Start by reading the specification for what you're trying to replace. The specification for integer division clearly states:

  1. The division rounds the result towards zero

  2. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs

  3. If the left operand is the smallest representable int and the right operand is –1, an overflow occurs. [...] it is implementation-defined as to whether [an ArithmeticException] is thrown or the overflow goes unreported with the resulting value being that of the left operand.

  4. If the value of the right operand is zero, a System.DivideByZeroException is thrown.

What we want is an integer division function which computes the quotient but rounds the result always upwards, not always towards zero.

So write a specification for that function. Our function int DivRoundUp(int dividend, int divisor) must have behaviour defined for every possible input. That undefined behaviour is deeply worrying, so let's eliminate it. We'll say that our operation has this specification:

  1. operation throws if divisor is zero

  2. operation throws if dividend is int.minval and divisor is -1

  3. if there is no remainder -- division is 'even' -- then the return value is the integral quotient

  4. Otherwise it returns the smallest integer that is greater than the quotient, that is, it always rounds up.

Now we have a specification, so we know we can come up with a testable design. Suppose we add an additional design criterion that the problem be solved solely with integer arithmetic, rather than computing the quotient as a double, since the "double" solution has been explicitly rejected in the problem statement.

So what must we compute? Clearly, to meet our spec while remaining solely in integer arithmetic, we need to know three facts. First, what was the integer quotient? Second, was the division free of remainder? And third, if not, was the integer quotient computed by rounding up or down?

Now that we have a specification and a design, we can start writing code.

public static int DivRoundUp(int dividend, int divisor)
{
  if (divisor == 0 ) throw ...
  if (divisor == -1 && dividend == Int32.MinValue) throw ...
  int roundedTowardsZeroQuotient = dividend / divisor;
  bool dividedEvenly = (dividend % divisor) == 0;
  if (dividedEvenly) 
    return roundedTowardsZeroQuotient;

  // At this point we know that divisor was not zero 
  // (because we would have thrown) and we know that 
  // dividend was not zero (because there would have been no remainder)
  // Therefore both are non-zero.  Either they are of the same sign, 
  // or opposite signs. If they're of opposite sign then we rounded 
  // UP towards zero so we're done. If they're of the same sign then 
  // we rounded DOWN towards zero, so we need to add one.

  bool wasRoundedDown = ((divisor > 0) == (dividend > 0));
  if (wasRoundedDown) 
    return roundedTowardsZeroQuotient + 1;
  else
    return roundedTowardsZeroQuotient;
}

Is this clever? No. Beautiful? No. Short? No. Correct according to the specification? I believe so, but I have not fully tested it. It looks pretty good though.

We're professionals here; use good engineering practices. Research your tools, specify the desired behaviour, consider error cases first, and write the code to emphasize its obvious correctness. And when you find a bug, consider whether your algorithm is deeply flawed to begin with before you just randomly start swapping the directions of comparisons around and break stuff that already works.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 1
    Would you really consider the unspecified behaviour for int.MinValue and -1 undesirable since the specification says it only occurs in unchecked contexts? Surely if the program is executing a division within an unchecked context we should assume that they are specifically trying to avoid the exception? – jerryjvl May 30 '09 at 00:22
  • 64
    What I care about is not the behaviour; either behaviour seems justifiable. What I care about is that it's not _specified_, which means it cannot easily be tested. In this case, we're defining our own operator, so we can specify whatever behaviour we like. i don't care whether that behaviour is "throw" or "don't throw", but I do care that it be stated. – Eric Lippert May 30 '09 at 06:27
  • 1
    That's a good point. Out of curiosity, do you have any idea why the second case may have been left unspecified in the specification of the language of all things? – jerryjvl Jun 01 '09 at 00:29
  • 5
    I suspect the first two sentences of this answer could be applied to a vast array of topics by replacing "integer arithmetic" with the name of the topic. As a matter of pedantry, I'd also consider changing the specification from "greater than the quotient" to "greater than or equal to the quotient". Otherwise DivRoundUp(12, 2) should return 7, as the smallest integer greater than 6. – Jon Skeet Jun 01 '09 at 16:15
  • 19
    @Jon: DivRoundUp(12, 2) falls into case (3) of the spec, not case (4). – Eric Lippert Jun 03 '09 at 15:03
  • @jerryjvl: I'm not certain, but my _guess_ would be that some hardware makes it cheap to detect this case and some does not. – Eric Lippert Jun 03 '09 at 15:05
  • 2
    I've learned from rounding issues in VBA and MySQL pre 5.0 (which I both believe had rounding issues based on problems with the way C implemented rounding) never to rounding as implemented in a language (though perhaps it has gotten better). I almost always end up writing my own methods or operators so I know *exactly* what to expect in every situation. Well done. – Ben McCormack Nov 19 '09 at 16:54
  • 16
    I think this is one of the best answers on the entire of SO. – Iain Galloway Jul 08 '10 at 14:51
  • 23
    This shakes me at my core - Jon Skeet..wrong? In any case, good answer. – Matt Mitchell Oct 20 '10 at 04:14
  • 5
    I saw this (fantastic answer) and wondered why Eric didn't use `Math.DivRem` instead of performing the division twice ('/' and '%'). Then I looked at the source code for Math.DivRem. It performs the division twice. Most microprocessors provide both quotient and remainder from a single div instruction, but I suppose not all. Still, if Math.DivRem had been implemented inside the CLR, it could have been optimized for processors that return both results. Disappointing. – Tergiver Jan 15 '11 at 18:29
  • 2
    @Tergiver or perhaps the jitter is intelligent enough that it doesn't need the extra hint, and recognizes that it can reduce division and modulo with the same denominator to a single instruction. – CodesInChaos Apr 06 '11 at 09:57
  • 1
    @CodeInChaos: Maybe. As a pessamist, I'm more inclined to believe that people are simply getting lazy. The purpose of a DivRem library method is to provide the opportunity to optimize it to a single division for languages that don't support multiple return values. Now granted, division isn't the beast it used to be and this isn't a big deal unless you are doing a lot of DivRems in a loop. My problem is: Why include a library method whos sole purpose is to provide opportunity to optimize when it doesn't appear there is any optimization? – Tergiver Apr 06 '11 at 16:05
  • 77
    @finnw: Whether I've tested it or not is irrelevant. Solving this integer arithmetic problem isn't *my* business problem; if it were, then I'd be testing it. If someone wants to take code from strangers off the internet to solve their business problem then the onus is on *them* to thoroughly test it. – Eric Lippert May 04 '11 at 16:21
  • 2
    Eric, instead of `bool wasRoundedDown = ((divisor > 0) == (dividend > 0))`, do you think `bool wasRoundedDown = Math.sign(divisor) == Math.sign(dividend)` reads better to communicate the logic as mentioned in the comment above? Just wondering. – SolutionYogi Dec 12 '11 at 19:12
  • 1
    @SolutionYogi: I think either would be fine. – Eric Lippert Dec 12 '11 at 19:30
  • 1
    Nice answer. I am using unsigned ints. I'm pretty sure I can skip the check for (int.minValue / -1), and the check for rounded down without problem. Agree? – Jeff Walker May 03 '12 at 16:19
  • 6
    @EricLippert "We're professionals here" Putting my pedantry cap on (and it's very spiffing): Stack Overflow isn't just for professionals, it's for hobbyists as well. So this statement is incorrect, even if that in no way diminishes your actual point. Phew, now I've got that off my chest I can sleep at night. – Rushyo Aug 30 '12 at 15:25
  • 2
    Why did you not just use the remainder to determine the direction it was rounded? `bool wasRoundedDown = (dividend % divisor) > 0;` – ILMTitan Apr 17 '13 at 22:55
  • @ILMTitan: That would be a perfectly reasonable alternative solution. – Eric Lippert Apr 17 '13 at 23:01
  • 2
    The above program *is* beautiful. We shouldn't think of beauty as terse or complicated - we should see beauty as enlightening. Only issue with a nice answer :). – Polymer Feb 12 '14 at 17:56
  • Modulo arithmetic is comparatively slow (on some machines - unless the CPU spits out modulo and quotient as part of a single operation, as some do; but compilers don't always take advantage of that). In most cases, computing `roundedTowardsZeroQuotient * divisor == dividend` is more efficient than `divisor % dividend == 0`. – Floris Jun 28 '14 at 14:42
55

All the answers here so far seem rather over-complicated.

In C# and Java, for positive dividend and divisor, you simply need to do:

( dividend + divisor - 1 ) / divisor 

Source: Number Conversion, Roland Backhouse, 2001

Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
  • Awesome. Although, you should've added the parentheses, to remove the ambiguities.The proof for it was a bit lengthy, but you can feel it in the gut, that it is right, just by looking at it. – Jörgen Sigvardsson Dec 05 '10 at 20:37
  • 2
    Hmmm... what about dividend=4, divisor=(-2)??? 4 / (-2) = (-2) = (-2) after being rounded up. but the algorithm you provided (4 + (-2) - 1) / (-2) = 1 / (-2) = (-0.5) = 0 after being rounded up. – Scott Feb 17 '11 at 21:41
  • 2
    @Scott - sorry, I omitted to mention that this solution only holds for positive dividend and divisor. I have updated my answer to mention clarify this. – Ian Nelson Feb 18 '11 at 08:44
  • +1. It is a simple and intuitive solution I have used already many times. – Olivier Jacot-Descombes Dec 13 '11 at 13:59
  • This is a good simple solution to a very common problem even if it does not cover the general case. Here is an alternate solution using modulo: ((dividend - 1) % divisor) + 1 – PIntag Jun 13 '13 at 16:45
  • 1
    i like it, of course you could have a somewhat artificial overflow in the numerator as a byproduct of this approach ... – TCC Oct 11 '13 at 20:52
  • 3
    @PIntag: The idea is good, but the use of modulo wrong. Take 13 and 3. Expected result 5, but `((13-1)%3)+1)` gives 1 as result. Taking the right kind of division, `1+(dividend - 1)/divisor` gives the same result as the answer for positive dividend and divisor. Also, no overflow problems, however artificial they may be. – Lutz Lehmann Mar 08 '14 at 21:46
  • Thanks for the correction, @LutzL. Not sure what I was thinking when I posted that last year :( – PIntag Mar 10 '14 at 19:10
  • This turned only up because it was linked this answer in a recent question http://stackoverflow.com/q/22254005/3088138, and I gave the comment that this answer, improved by your remark, is the most elegant way to express the wanted calculation, the other solutions were much too complicated. – Lutz Lehmann Mar 10 '14 at 19:17
  • 1
    @LutzL: I appreciate you giving me some credit for helping you to improve the answer, but I recognize that my "improvement" was an embarrassing failure. Your graciousness and diplomacy in this matter is appreciated - for that - vielen dank. – PIntag Mar 12 '14 at 21:06
48

The final int-based answer

For signed integers:

int div = a / b;
if (((a ^ b) >= 0) && (a % b != 0))
    div++;

For unsigned integers:

int div = a / b;
if (a % b != 0)
    div++;

The reasoning for this answer

Integer division '/' is defined to round towards zero (7.7.2 of the spec), but we want to round up. This means that negative answers are already rounded correctly, but positive answers need to be adjusted.

Non-zero positive answers are easy to detect, but answer zero is a little trickier, since that can be either the rounding up of a negative value or the rounding down of a positive one.

The safest bet is to detect when the answer should be positive by checking that the signs of both integers are identical. Integer xor operator '^' on the two values will result in a 0 sign-bit when this is the case, meaning a non-negative result, so the check (a ^ b) >= 0 determines that the result should have been positive before rounding. Also note that for unsigned integers, every answer is obviously positive, so this check can be omitted.

The only check remaining is then whether any rounding has occurred, for which a % b != 0 will do the job.

Lessons learned

Arithmetic (integer or otherwise) isn't nearly as simple as it seems. Thinking carefully required at all times.

Also, although my final answer is perhaps not as 'simple' or 'obvious' or perhaps even 'fast' as the floating point answers, it has one very strong redeeming quality for me; I have now reasoned through the answer, so I am actually certain it is correct (until someone smarter tells me otherwise -furtive glance in Eric's direction-).

To get the same feeling of certainty about the floating point answer, I'd have to do more (and possibly more complicated) thinking about whether there is any conditions under which the floating-point precision might get in the way, and whether Math.Ceiling perhaps does something undesirable on 'just the right' inputs.

The path travelled

Replace (note I replaced the second myInt1 with myInt2, assuming that was what you meant):

(int)Math.Ceiling((double)myInt1 / myInt2)

with:

(myInt1 - 1 + myInt2) / myInt2

The only caveat being that if myInt1 - 1 + myInt2 overflows the integer type you are using, you might not get what you expect.

Reason this is wrong: -1000000 and 3999 should give -250, this gives -249

EDIT:
Considering this has the same error as the other integer solution for negative myInt1 values, it might be easier to do something like:

int rem;
int div = Math.DivRem(myInt1, myInt2, out rem);
if (rem > 0)
  div++;

That should give the correct result in div using only integer operations.

Reason this is wrong: -1 and -5 should give 1, this gives 0

EDIT (once more, with feeling):
The division operator rounds towards zero; for negative results this is exactly right, so only non-negative results need adjustment. Also considering that DivRem just does a / and a % anyway, let's skip the call (and start with the easy comparison to avoid modulo calculation when it is not needed):

int div = myInt1 / myInt2;
if ((div >= 0) && (myInt1 % myInt2 != 0))
    div++;

Reason this is wrong: -1 and 5 should give 0, this gives 1

(In my own defence of the last attempt I should never have attempted a reasoned answer while my mind was telling me I was 2 hours late for sleep)

jerryjvl
  • 19,723
  • 7
  • 40
  • 55
  • [Fast ceiling of an integer division in C / C++](https://stackoverflow.com/q/2745074/995714) – phuclv May 30 '21 at 06:32
19

Perfect chance to use an extension method:

public static class Int32Methods
{
    public static int DivideByAndRoundUp(this int number, int divideBy)
    {                        
        return (int)Math.Ceiling((float)number / (float)divideBy);
    }
}

This makes your code uber readable too:

int result = myInt.DivideByAndRoundUp(4);
joshcomley
  • 28,099
  • 24
  • 107
  • 147
17

You could write a helper.

static int DivideRoundUp(int p1, int p2) {
  return (int)Math.Ceiling((double)p1 / p2);
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
2

You could use something like the following.

a / b + ((Math.Sign(a) * Math.Sign(b) > 0) && (a % b != 0)) ? 1 : 0)
Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
  • That's a nice one, although using (int)(float + 0.5f) could be a bit easier to understand. Also, it uses a division, a modulo, an add and an if (or somewhat similar), so it's damn slow :) – schnaader May 28 '09 at 14:43
  • But it uses only integer operations and they are damn fast compared to floating point operations. – Daniel Brückner May 28 '09 at 14:45
  • But I am not yet satisfied - I believe there is a very smart integer arithmetic hack ... going to think about it a bit ... – Daniel Brückner May 28 '09 at 14:47
  • Good point - also I didn't realize that the division will be done in any case, and an integer division is much faster than a float division. – schnaader May 28 '09 at 14:50
  • 13
    This code is obviously wrong in two ways. First off, there is a minor error in syntax; you need more parentheses. But more importantly, it does not compute the desired result. For example, try testing with a=-1000000 and b = 3999. The regular integer division result is -250. The double division is -250.0625... The desired behaviour is to round up. Clearly the correct rounding up from -250.0625 is to round up to -250, but your code rounds up to -249. – Eric Lippert May 28 '09 at 16:17
  • You are right. Going to fix the parenthesis and the logic. I messed the logic - should be smaller than zero and or instead of and. – Daniel Brückner May 29 '09 at 01:59
  • Inverting the whole expression makes it more understandable, I think. If a * b > 0 and a % b != 0, add one. – Daniel Brückner May 29 '09 at 02:03
  • 3
    The code is still wrong. Try it with a = +1000000 and b = +3999. The integer division is 250, the double division is 250.06, so it should be rounded up to 251. Your code gives the result of 250. Why are you multiplying? Multiplication gives you nothing useful. If what you want to do is compare the sign of "a" to the sign of "b" then surely the sensible way to do that is ((a>0)==(b>0)), no? – Eric Lippert May 29 '09 at 05:16
  • The code is theoretical correct, but I missed that the multiplication overflows. I used the multiplication to avoid another division and because the adjustment is required if a < 0 and b < 0 or a > 0 or b > 0. For this a * b > 0 was the shortest correct solution. ((a > 0) == (b > 0)) fails (at least) for a == 0 and b == 0. – Daniel Brückner May 29 '09 at 13:52
  • 3
    (1) using "a*b>0" is not the _shortest correct solution_ because it is _not a correct solution_. and (2), if a==0 and b==0 then you just divided zero by zero, so you've already thrown an exception. – Eric Lippert May 29 '09 at 14:58
  • 36
    I'm sorry to have to keep saying this but your code is STILL WRONG Daniel. 1/2 should round UP to 1, but your code rounds it DOWN to 0. Every time I find a bug you "fix" it by introducing another bug. My advice: stop doing that. When someone finds a bug in your code, don't just slap together a fix without thinking through clearly what caused the bug in the first place. Use good engineering practices; find the flaw in the algorithm and fix it. The flaw in all three incorrect versions of your algorithm is that you are not correctly determining when the rounding was "down". – Eric Lippert May 29 '09 at 16:23
  • 8
    Unbelievable how many bugs can be in this small piece of code. I did never have much time to think about it - the result manifests in the comments. (1) a * b > 0 would be correct if it did not overflow. There are 9 combinations for the sign of a and b - [-1, 0, +1] x [-1, 0, +1]. We can ignore the case b == 0 leaving the 6 cases [-1, 0, +1] x [-1, +1]. a / b rounds towards zero, that is rounding up for negative results and rounding down for positve resuls. Hence the adjustment must be performed if a and b have the same sign and are not both zero. – Daniel Brückner May 30 '09 at 10:24
  • a * b > 0 does exactly this because a * b is positive if and only if a and b are both positive or both negative. (2) The bug introduced by the devision is the same that would occur in the code you posted in a removed comment (result = a / b; if ((result > 0) && (a % b != 0)) result++;) because the sign is not correctly detected if the divisions rounds down to zero. (c) You are right with my comment on ((a > 0) == (b > 0)). But I wrote at least and indeed it fails for a = 0 and b < 0. – Daniel Brückner May 30 '09 at 10:37
  • (0 > 0) == (-1 > 0) is obviously true, but 0 / -1 should not be adjusted. Actually the second test - a % b != 0 - will evaluate to false and in turn no adjustment will be done, but it does not express the idea very well. – Daniel Brückner May 30 '09 at 11:10
  • Too clever by half. Is it understandable? – Jeremy McGee Nov 20 '09 at 08:40
  • 6
    This answer is probably the worst thing I wrote on SO ... and it is now linked by Eric's blog... Well, my intention was not to give a readable solution; I was really locking for a short and fast hack. And to defend my solution again, I got the idea right the first time, but did not think about overflows. It was obviously my mistake to post the code without writing and testing it in VisualStudio. The "fixes" are even worse - I did not realize that it was an overflow problem and thought I made an logical mistake. In consequence the first "fixes" did not change anything; I just inverted the – Daniel Brückner Nov 20 '09 at 12:05
  • 11
    logic and pushed the bug around. Here I made the next mistakes; as Eric already mentioned I did not really analyze the bug and just did the first thing that seemed right. And I still did not use VisualStudio. Okay, I was in a hurry and did not spend more then five minutes on the "fix", but this should not be an excuse. After I Eric repeatedly pointed out the bug, I fired up VisualStudio and found the real problem. The fix using Sign() makes the thing even more unreadable and turns it into code you don't really want to maintain. I learned my lesson and will no longer underestimate how tricky – Daniel Brückner Nov 20 '09 at 12:12
  • 4
    seemingly simple things may become. – Daniel Brückner Nov 20 '09 at 14:15
  • Isnt it rather convoluted and inefficient? – Eniola Jul 09 '16 at 17:30
0

For signed or unsigned integers.

q = x / y + !(((x < 0) != (y < 0)) || !(x % y));

For signed dividends and unsigned divisors.

q = x / y + !((x < 0) || !(x % y));

For unsigned dividends and signed divisors.

q = x / y + !((y < 0) || !(x % y));

For unsigned integers.

q = x / y + !!(x % y);

Zero divisor fails (as with a native operation).

Cannot overflow.

Elegant and correct.

The key to understanding the behavior is to recognize the difference in truncated, floored and ceilinged division. C#/C++ is natively truncated. When the quotient is negative (i.e. the operators signs are different) then truncation is a ceiling (less negative). Otherwise truncation is a floor (less positive).

So, if there is a remainder, add 1 if the result is positive. Modulo is the same, but you instead add the divisor. Flooring is the same, but you subtract under the reversed conditions.

evoskuil
  • 1,011
  • 1
  • 7
  • 13
0

By round up, I take it you mean away form zero always. Without any castings, use the Math.DivRem() function

/// <summary>
/// Divide a/b but always round up
/// </summary>
/// <param name="a">The numerator.</param>
/// <param name="b">The denominator.</param>
int DivRndUp(int a, int b)
{
    // remove sign
    int s = Math.Sign(a) * Math.Sign(b);
    a = Math.Abs(a);
    b = Math.Abs(b);
    var c = Math.DivRem(a, b, out int r);
    // if remainder >0 round up
    if (r > 0)
    {
        c++;
    }
    return s * c;
}

If roundup means always up regardless of sign, then

/// <summary>
/// Divide a/b but always round up
/// </summary>
/// <param name="a">The numerator.</param>
/// <param name="b">The denominator.</param>
int DivRndUp(int a, int b)
{
    // remove sign
    int s = Math.Sign(a) * Math.Sign(b);
    a = Math.Abs(a);
    b = Math.Abs(b);
    var c = Math.DivRem(a, b, out int r);
    // if remainder >0 round up
    if (r > 0)
    {
        c+=s;
    }
    return s * c;
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133
-2

Some of the above answers use floats, this is inefficient and really not necessary. For unsigned ints this is an efficient answer for int1/int2:

(int1 == 0) ? 0 : (int1 - 1) / int2 + 1;

For signed ints this will not be correct

-4

The problem with all the solutions here is either that they need a cast or they have a numerical problem. Casting to float or double is always an option, but we can do better.

When you use the code of the answer from @jerryjvl

int div = myInt1 / myInt2;
if ((div >= 0) && (myInt1 % myInt2 != 0))
    div++;

there is a rounding error. 1 / 5 would round up, because 1 % 5 != 0. But this is wrong, because rounding will only occur if you replace the 1 with a 3, so the result is 0.6. We need to find a way to round up when the calculation give us a value greater than or equal to 0.5. The result of the modulo operator in the upper example has a range from 0 to myInt2-1. The rounding will only occur if the remainder is greater than 50% of the divisor. So the adjusted code looks like this:

int div = myInt1 / myInt2;
if (myInt1 % myInt2 >= myInt2 / 2)
    div++;

Of course we have a rounding problem at myInt2 / 2 too, but this result will give you a better rounding solution than the other ones on this site.

raboni
  • 1
  • "We need to find a way to round up when the calculation give us a value greater than or equal to 0.5" - you've missed the point of this question - or always round up i.e. the OP wants to round up 0.001 to 1 . – Grhm Jan 30 '13 at 13:37