Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up to the next integer? [duplicate]

Tags:

java

math

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?

like image 321
membersound Avatar asked Oct 30 '13 16:10

membersound


2 Answers

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);
like image 80
kviiri Avatar answered Nov 15 '22 09:11

kviiri


You can use this expression (assuming a and b are positive)

(a+b-1)/b
like image 26
Henry Avatar answered Nov 15 '22 08:11

Henry