Library contents

Java Math.round

Math.round returns the nearest whole number. A delivery screen can turn a decimal estimate into a number of minutes that is easier to read.

A simple example

Math.round

  1. Start with 2.6
  2. Do this Round to the nearest integer
  3. Result 3
The distance to 3 is 0.4. The distance to 2 is 0.6.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.round(2.6));
    }
}
Output
3

Syntax

Java syntax
long minutes = Math.round(estimate);
JDK 21 method signatures (2)
public static int round(float a)
public static long round(double a)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Display two estimates

A scheduling screen compares two estimates that are presented using the same display convention. Apply the chosen conversion consistently to both inputs so the operator can read them side by side.

First output line12 minutes
Main.java
public class Main {
    public static void main(String[] args) throws Exception {
        for (double estimate : new double[]{12.4, 12.5}) {
            System.out.println(Math.round(estimate) + " minutes");
        }
    }
}
Output
12 minutes
13 minutes

The first estimate is closer to 12. The second is exactly halfway, so the displayed estimate becomes 13.

Advertisements

Show a bus arrival on a station board

A transit or delivery display has room only for whole minutes. Convert a fractional estimate for display while keeping the more precise original estimate available to the scheduler.

From the programdouble minutes = 7.8
Result8.000
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        double minutes = 7.8;

        System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.round(minutes)));
    }
}
Output
8.000

A 7.8-minute prediction displays as eight minutes. Keep the full estimate for scheduling calculations.

Round a parcel reading for a whole-unit display

A mailroom display shows only whole grams while its scale records tenths. A parcel weighs 18.7 grams and the display rounds to the nearest gram.

Given18.7 g → nearest whole gram
Worked result19 g

The reading lies closer to nineteen than eighteen.

What to watch for

At an exact half, Math.round chooses the integer toward positive infinity. For example, −1.5 becomes −1. For a monetary rounding policy, use BigDecimal.

Documentation for Math.round