How to Round Numbers (double, float) in Java to Number of Decimal Places

<rant>For some strange reason, Java doesn’t have the ability to round numbers to a given number of decimals. This seems like such an obvious thing to include in any programming language.</rant> Anyway, you can round to the nearest integer, so you have to a little workaround to round to a given number of decimal places. The method below will do this.

public class MathUtility
{
    public static double Round(double number, int decimalPlaces)
    {
	double modifier = Math.pow(10.0, decimalPlaces);
	return Math.round(number * modifier) / modifier;
    }
}

To test this method, I developed the following simple method.

public static boolean Test(double expected, double actual)
{
    boolean result = expected == actual;
 
    if (!result)
	System.out.println("Expected: " + expected + ", Actual: " + actual);
 
    return result;
}

And then I tested the rounding method using the following code (the tests all passed):

System.out.println(Test(1, MathUtility.Round(1.12345678, 0)));
System.out.println(Test(1.1, MathUtility.Round(1.12345678, 1)));
System.out.println(Test(1.12, MathUtility.Round(1.12345678, 2)));
System.out.println(Test(1.123, MathUtility.Round(1.12345678, 3)));
System.out.println(Test(1.1235, MathUtility.Round(1.12345678, 4)));
System.out.println(Test(1.12346, MathUtility.Round(1.12345678, 5)));
System.out.println(Test(1.123457, MathUtility.Round(1.12345678, 6)));
System.out.println(Test(1.1234568, MathUtility.Round(1.12345678, 7)));
System.out.println(Test(1.12345678, MathUtility.Round(1.12345678, 8)));

2 Responses to “How to Round Numbers (double, float) in Java to Number of Decimal Places”

  1. Thank you! Good Work

  2. I tried the following and the result was not good.

    public static void main(String[] args) {
    double d;

    d = 19.435;
    System.out.println(d);
    System.out.println((int) (d * 100));
    System.out.println(“——————————-”);
    System.out.println(“Round = ” + Round(d * 100, 0));
    System.out.println(“roundDecimal = ” + roundDecimal(d * 100, 0));

    }

    static double Round(double number, int decimalPlaces)
    {
    double modifier = Math.pow(10.0, decimalPlaces);
    return Math.round(number * modifier) / modifier;
    }

    result:
    19.435
    1943
    ——————————-
    Round = 1943.0

    Result should be 1944.

Leave a Reply