How to Round a Number to N decimal Places in Java Example
In this example tutorial, you will learn how to round a number to n decimal places in Java.
Rounding Number with DecimalFormat
You can use the DecimalFormat class to format decimal numbers. The DecimalFormat class uses a string pattern to format the number. This pattern determines what the formatted numbers look like.
Let's round a number to two decimal places using the DecimalFormat class:
DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
double num = 142056.1679;
String formattedNum = decimalFormat.format(num);
Double roundedNum = Double.parseDouble(formattedNum);
The above code will give the following output:
142056.17
Refer to the table below to determine the output based on the pattern used:
Number | Pattern | Output | Explanation |
---|---|---|---|
184883.126 | ###,###.### | 184,883.126 | The # sign denotes a digit, the comma sign is the placeholder for a grouping separator, and the period sign is the placeholder for decimal point. |
184883.126 | ###.## | 184883.12 | The pattern has two decimal places and three digits to the right of the decimal point. |
275.15 | 000000.000 | 000275.150 | The use of 0 determines leading and trailing zeros. |
Rounding Number with BigDecimal
To round a number to 2 decimal places with BigDecimal:
double value = 142056.1679;
BigDecimal bigDecimal = new BigDecimal(Double.toString(value));
bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
The above code will give the following output:
142056.17