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
- Start with 2.6
- Do this Round to the nearest integer
- Result 3
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.round(2.6));
}
}
3
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.javaDisplay 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.
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");
}
}
}
12 minutes 13 minutes
The first estimate is closer to 12. The second is exactly halfway, so the displayed estimate becomes 13.
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.
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)));
}
}
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.
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.