What is the correct way to round a division of two integers up to the next integer?
int a = 3;
int b = 2;
a / b = ? //should give 2
Is Math.ceil()
the right way to go?
No, Math.ceil()
won't work on its own because the problem occurs earlier. a
and b
are both integers, so dividing them evaluates to an integer which is the floor of the actual result of the division. For a = 3
and b = 2
, the result is 1
. The ceiling of one is also one - hence you won't get the desired result.
You must fix your division first. By casting one of the operands to a floating point number, you get a non-integer result as desired. Then you can use Math.ceil
to round it up. This code should work:
Math.ceil((double)a / b);
You can use this expression (assuming a and b are positive)
(a+b-1)/b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With