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

  1. public class Decimal {
  2. public static void main(String[] args) {
  3. double num = 1.34567;
  4. System.out.format("%.4f", num);
  5. }
  6. }

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

  1. import java.math.RoundingMode;
  2. import java.text.DecimalFormat;
  3. public class Decimal {
  4. public static void main(String[] args) {
  5. double num = 1.34567;
  6. DecimalFormat df = new DecimalFormat("#.###");
  7. df.setRoundingMode(RoundingMode.CEILING);
  8. System.out.println(df.format(num));
  9. }
  10. }

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.