Java Program to Round a Number to n Decimal Places

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Round a Number using format

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;

        System.out.format("%.4f", num);
    }
}

Output

1.3457

In the above program, we've used the format() method to print the given floating-point number num to 4 decimal places.  The 4 decimal places are given by the format .4f.

This means, print only up to 4 places after the dot (decimal places), and f means to print the floating-point number.


Example 2: Round a Number using DecimalFormat

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

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;
        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);

        System.out.println(df.format(num));
    }
}

Output

1.346

In the above program, we've used DecimalFormat class to round a given number num.

We declare the format using the # patterns #.###. This means we want num up to 3 decimal places. We also set the rounding mode to Ceiling, this causes the last given place to be rounded to its next number.

So, 1.34567 rounded to 3 decimal places prints 1.346, 6 is the next number for 3rd place decimal 5.

Did you find this article helpful?