In Java, Math.round(a) returns the whole number closest to a. Exact halves round up, toward positive infinity: Math.round(2.5) is 3 and Math.round(-2.5) is -2.
Unlike ceil, floor, and rint, it returns an integer type: a long for a double argument and an int for a float. It is the usual choice for rounding prices for display, as in Math.round(x * 100) / 100.0.
A static method of the java.lang.Math class, available since the early versions of Java (JDK 1.0). Call it on the class name, as in Math.round(...). No import is needed, because classes in java.lang are always visible.
Syntax
Pass a double to get a long, or a float to get an int.
Java
long a = Math.round(2.5); // 3
long b = Math.round(-2.5); // -2
int c = Math.round(2.5f); // 3 (float version)
double cents = Math.round(x * 100) / 100.0; // two decimals
Call
What it does
Math.round(7.49)
Returns the long 7.
Math.round(7.5f)
float overload: returns the int 8.
Math.round(price * 100) / 100.0
Round to two decimal places (a double).
(int) Math.round(x)
Nearest int, if you know the value fits.
Since Java 7, round gives the mathematically correct answer even for values just below .5, such as 0.49999999999999994, which rounds to 0. Very old Java versions computed floor(a + 0.5) and returned 1 there.
Library declarations
Java
// java.lang.Math
public static int round(float a)
public static long round(double a)
Parameters
Parameter
Description
a
The float or double to round. An int or long argument is widened to float, so cast it to double if precision matters.
Return Value
Return Value
Description
int (for float)
The nearest int; ties go toward positive infinity.
long (for double)
The nearest long. NaN gives 0; values beyond the range give Long.MAX_VALUE or Long.MIN_VALUE (Integer limits for the float version).
NaN becomes 0. An integer cannot be "not a number", so round returns 0 instead of throwing.
Saturation, not overflow. 1e20 is bigger than any long, so the result is capped at Long.MAX_VALUE; the float version caps 1e10f at Integer.MAX_VALUE.
The cast still wraps.Math.round(3e9) is the correct long 3000000000, but (int) keeps only the low 32 bits, giving -1294967296.
Frequently Asked Questions
The nearest whole number. For a double argument it returns a long, and for a float argument it returns an int. Exact halves round toward positive infinity.
Use Math.round(x * 100) / 100.0 for display, or String.format("%.2f", x) to get text. For exact money calculations, use BigDecimal with setScale(2, RoundingMode.HALF_UP).
Because round sends exact halves toward positive infinity, and -2 is greater than -3. Values past the halfway point, such as -2.6, still round to -3.
Because Math.round(double) returns a long. Write (int) Math.round(3.7), or pass a float: Math.round(3.7f) returns an int.
It returns 0. Values too large for the result type are capped at Long.MAX_VALUE or Long.MIN_VALUE (Integer limits for the float version).