How to Round a Number in Java

Java provides Math.round() for half-up rounding, Math.ceil() and Math.floor() for ceiling/floor, and BigDecimal for precise rounding to a specific number of decimal places.

Math.round() β€” nearest integer, half-up

Math.round(3.5);   // 4  (rounds half up)
Math.round(3.4);   // 3
Math.round(-3.5);  // -3 (rounds toward positive infinity β€” half-up)
Math.round(3.14);  // 3

// Returns long for double input:
long n = Math.round(3.99999);   // 4

// Returns int for float input:
int m = Math.round(3.9f);       // 4

Math.ceil() and Math.floor()

Math.ceil(3.1);   // 4.0 β€” always rounds up
Math.ceil(3.9);   // 4.0
Math.floor(3.9);  // 3.0 β€” always rounds down
Math.floor(3.1);  // 3.0

Round to N decimal places (the naive way)

double price = 3.14159;
double rounded = Math.round(price * 100.0) / 100.0;  // 3.14

This works for display but may have floating-point representation issues for financial calculations.

BigDecimal β€” precise rounding

import java.math.BigDecimal;
import java.math.RoundingMode;

BigDecimal bd = new BigDecimal("2.455");
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(rounded); // 2.46

Always construct BigDecimal from a String (not a double) to avoid floating-point representation errors:

new BigDecimal(2.455)    // 2.45499999999999... β€” floating-point garbage
new BigDecimal("2.455")  // exactly 2.455

RoundingMode options

ModeBehaviour
HALF_UPStandard rounding: 0.5 rounds away from zero
HALF_EVENBanker's rounding: ties round to nearest even digit
CEILINGAlways toward positive infinity
FLOORAlways toward negative infinity
DOWNToward zero (truncate)
UNNECESSARYThrows if rounding is required

String.format for display-only rounding

double price = 3.14159;
System.out.printf("%.2f%n", price);           // 3.14
String s = String.format("%.3f", price);      // "3.142"
String s2 = "%.2f".formatted(price);          // "3.14"

Note: format rounding is only for display β€” the underlying double value is unchanged.