Java Math.ceil
Math.ceil rounds toward positive infinity. When a table seats four people, any guests left over need one more table.
A simple example
Math.ceil
- Start with 2.3
- Do this Round upward to a whole number
- Result 3
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.ceil(2.3));
}
}
3.0
Syntax
Math.ceil(number)
JDK 21 method signatures (1)
public static double ceil(double a)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSeat nine guests
A booking clerk knows how many guests will arrive and how many fit at one table. Test a party that leaves a partial table so the final guest still has a seat.
public class Main {
public static void main(String[] args) throws Exception {
for (int guests : new int[]{8, 9}) {
int tables = (int) Math.ceil(guests / 4.0);
System.out.println(guests + " guests: " + tables + " tables");
}
}
}
8 guests: 2 tables 9 guests: 3 tables
Eight guests fill exactly two tables. Nine divided by four is 2.25, so the second booking needs three.
Book enough minibuses for a field trip
A teacher has 73 passengers on the museum trip, including the adults. Each minibus seats 24. She needs enough vehicles for the last passenger as well as the first 72.
class Main {
public static void main(String[] args) throws Exception {
int passengers = 73;
int seats = 24;
int buses = ((int) Math.ceil(passengers / (double) seats));
System.out.println(Integer.toString(buses) + " minibuses");
}
}
4 minibuses
Three minibuses seat 72 people. Dividing before rounding up reserves the fourth vehicle for the remaining passenger.
Pack badges for two classrooms
A teacher has 31 badges and uses trays that hold eight each. All badges must travel, including those in a partially filled tray.
Three trays carry 24 badges. The remaining seven need the fourth tray.
What to watch for
Divide using a double. Integer division discards the remainder before ceil can use it.