Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to round a number to 2 decimal places

Short answer

If you only need to display the number, format it — %.2f rounds to two digits:

void main() {
    double value = 3.14159;
    IO.println(String.format("%.2f", value));
}

Output:

3.14

%.2f uses the system language: with a German locale you see 3,14. To always get a dot, pass Locale.US as the first argument.

Rounding the value itself

To get a rounded double for further calculations, multiply by 100, round and divide back:

void main() {
    double value = 2.6789;
    double rounded = Math.round(value * 100) / 100.0;
 
    IO.println(rounded);
}

Output:

2.68

Exactly — with BigDecimal

BigDecimal.setScale() rounds without binary arithmetic errors and lets you choose the rounding rule. HALF_UP is the familiar school rule:

void main() {
    var price = new BigDecimal("2.345");
 
    IO.println(price.setScale(2, RoundingMode.HALF_UP));
    IO.println(price.setScale(2, RoundingMode.HALF_EVEN));
    IO.println(price.setScale(2, RoundingMode.DOWN));
}

Output:

2.35
2.34
2.34

HALF_EVEN is "banker's rounding": a half goes to the even digit.

Common mistake

Rounding a double and expecting an exact result. The number 1.005 is stored as 1.00499999…, so it rounds down:

void main() {
    IO.println(Math.round(1.005 * 100) / 100.0);
    IO.println(new BigDecimal("1.005").setScale(2, RoundingMode.HALF_UP));
}

Output:

1.0
1.01

For money and other exact values use a BigDecimal created from a string.

Functions used in this recipe

  • Math.round() — Rounds a number to the nearest integer.
  • BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
  • String.format() — Builds a string from a template with placeholders such as %s and %d.

Thanks for reading!

Donate to the site — we work hard for you.