The answer is Yes. Java does a round down in case of division of two integer numbers.
If the divisor and dividend have the same sign then the result is zero or positive. If the divisor and dividend have opposite signs then the result is zero or negative. If the division is inexact then the quotient is rounded up.
If you want to convert floating-point double value to the nearest int value then you should use the Math. round() method. It accepts a double value and converts into the nearest long value by adding 0.5 and truncating decimal points.
Use Math.ceil()
and cast the result to int:
Example:
(int) Math.ceil((double)divident / divisor);
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
Another one-liner that is not too complicated:
private int countNumberOfPages(int numberOfObjects, int pageSize) {
return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}
Could use long instead of int; just change the parameter types and return type.
Google's Guava library handles this in the IntMath class:
IntMath.divide(numerator, divisor, RoundingMode.CEILING);
Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.
(message.length() + 152) / 153
This will give a "rounded up" integer.
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
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