How to round decimal number with N digits after decimal point
- Details
- Written by Nam Ha Minh
- Last Updated on 02 July 2019   |   Print Email
- 7.2314 is rounded to 7.23 (two digits after decimal point).
- 8.3868 is rounded to 8.4 (one digit after decimal point).
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.
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:
- 10 Common Mistakes Every Beginner Java Programmer Makes
- 10 Java Core Best Practices Every Java Programmer Should Know
- How to become a good programmer? 13 tasks you should practice now
- How to calculate MD5 and SHA hash values in Java
- How to generate random numbers in Java
- Java File Encryption and Decryption Example
Comments