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?
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?
You can use this expression (assuming a and b are positive)
(a+b-1)/b
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);
The return type of Math.ceil method is double where is, the return type of Math.round is int. so if you want that, the result will be in integer then you should use Math.round method, or else Math.ceil method is fine.
float x = 1654.9874f;
System.out.println("Math.round(" + x + ")=" + Math.round(x));
System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x));
Math.round(1654.9874)=1655
Math.ceil(1654.9874)=1655.0
a division between 2 integers (also known as integer division
) yields the remaining of the division.
3/2 = 1
To use ceil, you need to make a division that is not integer.:
You can either declare your values as doubles (3.0
or 3d
) or cast them before dividing:
((double) 3) / ((double) 2) = 1.5
This double value can be used in ceil.
Math.ceil(3.0 / 2.0) = 2.0;