Library contents

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

  1. Start with 2.3
  2. Do this Round upward to a whole number
  3. Result 3
Two is below 2.3. Three is the first whole number at or above it.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.ceil(2.3));
    }
}
Output
3.0

Syntax

Java 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.java

Seat 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.

First output line8 guests: 2 tables
Main.java
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");
        }
    }
}
Output
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.

Advertisements

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.

Given73 passengers · 24 seats per minibus
Result4 minibuses
Main.java
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");
    }
}
Output
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.

Given31 badges · 8 per tray
Worked result4 trays

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.

Documentation for Math.ceil