In Java, the fastest and most convenient way to round a decimal number is using the BigDecimal class. Let’s say, we want to round some numbers like this:

  • 7.2314 is rounded to 7.23 (two digits after decimal point).
  • 8.3868 is rounded to 8.4 (one digit after decimal point).

Here’s a very simple utility class that rounds an arbitrary decimal number with the number of digits after decimal point can be specified:

package net.codejava.core;

import java.math.BigDecimal;

/**
 * This utility class rounds a decimal number.
 * @author www.codejava.net
 *
 */
public class DecimalUtils {

	public static double round(double value, int numberOfDigitsAfterDecimalPoint) {
		BigDecimal bigDecimal = new BigDecimal(value);
		bigDecimal = bigDecimal.setScale(numberOfDigitsAfterDecimalPoint, 
				BigDecimal.ROUND_HALF_UP);
		return bigDecimal.doubleValue();
	}
}

The important point in this utility class is the setScale() method of the BigDecimal class. It accepts two parameters:

  • The first parameter specifies number of digits after decimal point which the rounding will be carried out toward.
  • The second parameter specifies round mode. Here, we use the ROUND_HALF_UP which rounds up the number toward the “nearest neighbor”. The BigDecimal class defines all possible round modes, including ROUND_HALF_DOWN, ROUND_HALF_EVEN, etc.

And the following is a test program:

package net.codejava.core;

/**
 * Test rounding decimal numbers.
 * @author www.codejava.net
 *
 */
public class DecimalUtilsTest {

	public static void main(String[] args) {
		double number = 91.2139;
		double roundedNumber = DecimalUtils.round(number, 2);
		System.out.println(number + " is rounded to: " + roundedNumber);
		
		roundedNumber = DecimalUtils.round(number, 3);
		System.out.println(number + " is rounded to: " + roundedNumber);
		
		number = 80.37723;
		roundedNumber = DecimalUtils.round(number, 2);
		System.out.println(number + " is rounded to: " + roundedNumber);
		
		roundedNumber = DecimalUtils.round(number, 3);
		System.out.println(number + " is rounded to: " + roundedNumber);
	}

}

Output:

91.2139 is rounded to: 91.21

91.2139 is rounded to: 91.214

80.37723 is rounded to: 80.38

80.37723 is rounded to: 80.377

 

References:

 

Other Java Coding Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#1kb2016-05-13 14:19
Thank You for taking your time and posting this code. Worked great !!
Quote