How to round a number up or down
Short answer
Math.ceil() rounds up, Math.floor() rounds down, and Math.round() rounds to the nearest integer:
void main() {
double value = 4.3;
IO.println(Math.ceil(value));
IO.println(Math.floor(value));
IO.println(Math.round(value));
}Output:
5.0
4.0
4ceil() and floor() return a double, while round() returns a long.
How many pages
A typical rounding-up task is counting pages:
void main() {
int items = 47;
int perPage = 10;
int pages = (int) Math.ceil((double) items / perPage);
IO.println(pages);
IO.println(Math.ceilDiv(items, perPage));
}Output:
5
5Math.ceilDiv() (Java 18) does the same without decimals.
Negative numbers
"Down" means towards minus infinity, so floor(-4.3) is -5. Casting to int simply drops the fractional part:
void main() {
IO.println(Math.floor(-4.3));
IO.println((int) -4.3);
IO.println(Math.round(-4.5));
}Output:
-5.0
-4
-4Common mistake
Passing the result of integer division to Math.ceil(). The fractional part is already lost:
void main() {
int items = 47;
IO.println(Math.ceil(items / 10));
IO.println(Math.ceil(items / 10.0));
}Output:
4.0
5.0Functions used in this recipe
- Math.ceil() — Rounds up to the nearest integer that is greater than or equal.
- Math.floor() — Rounds down to the nearest integer that is less than or equal.
- Math.round() — Rounds a number to the nearest integer.
- BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.