Java Program to Round a Number to n Decimal Places

In this program, you'll learn to round a given number to n decimal places in Java.

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);
    }
}

When you run the program, the output will be:

1.3457

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

This means, print only upto 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));
    }
}

When you run the program, the output will be:

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 upto 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.