Round a Number to N decimal Places in Java

  • Last updated Apr 25, 2024

In this tutorial, we will learn how to round a number in Java using the DecimalFormat and BigDecimal class.

Rounding a number to a specified number of decimal places is often necessary to ensure precision and control over the decimal values in a computation or presentation. It also improves readability, and ensures conformance to requirements or standards in various domains.


Rounding a Number using DecimalFormat

This class is mainly used for formatting and rounding numbers for display purposes. It allows you to specify a specific format pattern, such as the number of decimal places, grouping separators, and currency symbols. It is useful when you want to control the appearance of numbers when presenting them to users or storing them as formatted strings. DecimalFormat provides options for rounding numbers, but it is not designed for precise mathematical calculations.

Here's a code snippet in Java to round a number using DecimalFormat:

DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);

double num = 142056.1679;

String formattedNum = decimalFormat.format(num);
Double roundedNum = Double.parseDouble(formattedNum);

In the first line, we create a new instance of the DecimalFormat class and pass the pattern #.## as a parameter. This pattern specifies that we want to round the number to two decimal places.

The second line sets the rounding mode of the DecimalFormat object to RoundingMode.HALF_UP. This means that if the decimal to be rounded is exactly halfway between two others (e.g., 0.005), it will be rounded up.

In the above code, we have a variable num which holds the original number we want to round.

Using the format() method of the DecimalFormat object, we format the number num according to the pattern we set earlier. The formatted result is stored in the formattedNum variable as a string.

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
###.##
184,883.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.


Example:

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Example {

   public static void main(String[] args) {
		
	DecimalFormat decimalFormat = new DecimalFormat("#.##");
	decimalFormat.setRoundingMode(RoundingMode.HALF_UP);

	double num = 142056.1679;

	String formattedNum = decimalFormat.format(num);
	Double roundedNum = Double.parseDouble(formattedNum);
	System.out.println(roundedNum);
		
   }

}

Output:

142056.17


Rounding a Number using BigDecimal

The BigDecimal class is used for precise arithmetic calculations with arbitrary precision. It is suitable for cases where accuracy is crucial, such as financial calculations or scientific computations. BigDecimal supports operations like addition, subtraction, multiplication, and division with arbitrary precision, and it avoids the rounding errors that can occur with floating-point numbers. BigDecimal allows you to control the scale (number of decimal places) and rounding modes for arithmetic operations, ensuring accurate results.

Here's a code snippet in Java to round a number using BigDecimal:

double value = 142056.1679;

BigDecimal bigDecimal = new BigDecimal(Double.toString(value));
bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);

In this code snippet, we have a double value 142056.1679. We want to round this value to 2 decimal places. To achieve this, we first create a BigDecimal object by converting the double value to a string using Double.toString(value). Then, we use the setScale method to specify the desired scale (number of decimal places) as 2 and the rounding mode as RoundingMode.HALF_UP.

The RoundingMode.HALF_UP rounding mode means that if the number to be rounded is halfway between two others, it is rounded towards the nearest neighbor that is away from zero.

After rounding, the updated BigDecimal object will hold the rounded value.


Example:

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

public class Example {

   public static void main(String[] args) {
		
	double value = 142056.1679;

	BigDecimal bigDecimal = new BigDecimal(Double.toString(value));
	bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
	System.out.println(bigDecimal);
   }

}

Output:

142056.17