1. Introduction
In real life, it’s rare that we need to see long “tails” after the decimal point. For example, when you calculate a product price, a salary, a GPA, or a room area, you usually only need a couple of digits after the decimal point, not 15.
For example, a division result:
double x = 10.0 / 3.0;
System.out.println(x); // 3.3333333333333335
A user seeing such a result might get startled and think the program went crazy. Therefore, numbers often need to be rounded — to the nearest integer, to two decimal places, and so on.
In Java there are several convenient tools for that.
2. Method Math.round(): rounding to the nearest integer
The simplest way to round a number is to use the Math.round() method. It takes a floating-point number (either float or double) and returns the nearest integer.
How Math.round works
- If the fractional part is less than 0.5 — it rounds down.
- If the fractional part is 0.5 or greater — it rounds up.
Examples:
System.out.println(Math.round(2.3)); // 2
System.out.println(Math.round(2.7)); // 3
System.out.println(Math.round(2.5)); // 3
System.out.println(Math.round(-2.5)); // -2
Return type
- If you pass a float, it returns an int.
- If you pass a double, it returns a long.
float f = 5.8f;
int roundedF = Math.round(f); // 6
double d = 5.8;
long roundedD = Math.round(d); // 6
Note: sometimes this is surprising — you rounded a double and got a long! If you need an int, you’ll have to make an explicit cast:
int rounded = (int) Math.round(5.6); // 6
3. Rounding to a specific number of decimal places
Often you need to round not to an integer but, for example, to two decimal places (for money, percentages, etc.).
Java does not have a “magic” method like Math.roundTo2Digits(), but you can do it manually.
Method 1: a math trick with multiplication and division
- Multiply the number by 100 (if you need two digits).
- Round to an integer using Math.round.
- Divide back by 100.
Example:
double value = 3.14159;
double rounded = Math.round(value * 100.0) / 100.0;
System.out.println(rounded); // 3.14
How it works:
- 3.14159 * 100 = 314.159
- Math.round(314.159) = 314
- 314 / 100.0 = 3.14
4. Number formatting: the DecimalFormat class
Sometimes you need not only to round a number but also to display it nicely — with a specific number of decimal places, leading zeros, grouping separators, etc. For that Java has the DecimalFormat class from the java.text package.
How DecimalFormat works
- Create an instance with the desired pattern.
- Call its format(...) method.
import java.text.DecimalFormat;
double value = 3.14159;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(value)); // 3.14
How the pattern works
- "0.00" — always two decimal places (even if the number is an integer).
- "0.###" — up to three decimal places; extra zeros are not printed.
- "#,##0.00" — adds thousands separators (for example, "1,234.56").
Examples of different patterns:
| Pattern | Number | Result |
|---|---|---|
|
2 | 2.00 |
|
2.5 | 2.50 |
|
2.567 | 2.57 |
|
2.567 | 2.567 |
|
2.5 | 2.5 |
|
12345.678 | 12,345.68 |
Example with thousands separators
DecimalFormat df = new DecimalFormat("#,##0.00");
System.out.println(df.format(1234567.89)); // 1,234,567.89
Example: output without trailing zeros
DecimalFormat df = new DecimalFormat("0.##");
System.out.println(df.format(3.1)); // 3.1
System.out.println(df.format(3.141)); // 3.14
System.out.println(df.format(3.145)); // 3.15
5. Formatting with String.format
Sometimes for simple cases it’s convenient to use String.format — a built-in way to format strings similar to printf in other languages.
double value = 3.14159;
System.out.println(String.format("%.2f", value)); // 3.14
Here "%.2f" means “print the number with two decimal places”.
Comparison of approaches:
- DecimalFormat — more powerful, supports patterns and localization, convenient for thousands separators.
- String.format — simpler when you just need to set the number of decimal places.
6. Rounding nuances: Math.floor, Math.ceil, Math.rint
- Math.floor(x) — rounds down (toward negative infinity), including for negative numbers.
- Math.ceil(x) — rounds up (toward positive infinity).
- Math.rint(x) — rounds to the nearest integer but returns a double.
Examples:
System.out.println(Math.floor(2.7)); // 2.0
System.out.println(Math.ceil(2.1)); // 3.0
System.out.println(Math.rint(2.5)); // 2.0 (yes — not a typo!)
System.out.println(Math.rint(3.5)); // 4.0
Attention: Math.rint sometimes rounds “to the nearest even” — this rule (so-called banker's rounding) helps reduce the accumulation of errors in bulk calculations.
7. Useful notes
Visualization: rounding table
| Number | Math.round | Math.floor | Math.ceil | Math.rint |
|---|---|---|---|---|
| 2.3 | 2 | 2.0 | 3.0 | 2.0 |
| 2.5 | 3 | 2.0 | 3.0 | 2.0 |
| 3.5 | 4 | 3.0 | 4.0 | 4.0 |
| -2.3 | -2 | -3.0 | -2.0 | -2.0 |
| -2.5 | -2 | -3.0 | -2.0 | -2.0 |
Rounding is not formatting!
It’s very important to understand the difference between rounding and formatting.
- Rounding — changes the value of a number (for example, 2.718 → 2.72).
- Formatting — changes how a number looks when printed (for example, 2.718 → "2.72" on the screen, but in memory it remains 2.718).
double x = 2.718;
System.out.println(String.format("%.2f", x)); // 2.72
System.out.println(x); // 2.718
If you want to use the rounded number in further calculations — round mathematically! If it’s only for output — format it.
8. Common mistakes when rounding and formatting numbers
Error #1: Rounded only for output, but then use the “long-tailed” number.
A very common situation is to print a nicely formatted value to the screen and then use the original “long” number in calculations. For money, scores, and totals — round first (for example, Math.round or the multiply/divide trick), then store/send it to the user.
Error #2: Expecting that Math.round(x) will return a double with two decimal places.
Math.round() always rounds to the nearest integer: for float it returns an int, and for double — a long. For two decimal places, use multiplication/division or formatting.
Error #3: Using DecimalFormat for calculations.
DecimalFormat.format() returns a string. You cannot use it in arithmetic: you’ll get a compilation error or a NumberFormatException when parsing back.
Error #4: Incorrect DecimalFormat pattern.
The pattern must match your expectations: "0.00" will always show two digits ("2.00"), while "0.##" removes extra zeros ("2", "2.1", "2.12").
Error #5: Loss of precision when dividing by 100.
If you divide an int by an int, the result is also an int!
int a = 5;
System.out.println(a / 2); // 2, not 2.5!
To make the division floating-point, at least one operand must be a double:
int a = 5;
System.out.println(a / 2.0); // 2.5
GO TO FULL VERSION