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:

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:

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 started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.