Java Program to Round a Number to n Decimal Places

In this java program, we will learn about have to round a number to N decimal places. Below is a example of the same:

Input: Number = 21.3498534263, round = 4
Output: 21.3499

Input: Number = 21.3498534263, round = 2
Output: 21.35

Decimal values that may be rounded to N decimal places are floating-point numbers. In Java, you may round a number to N decimal places in one of the following ways.


Java Program to Round a Decimal Number using Format Method

We can round a decimal number in java till N decimal places by using inbuilt format() method. Format method is used to print the given floating-point number to N decimal places. Here is the syntax of format() method.

System.out.format("%.nf", Number);

public class RoundNumberFormatMethod {
  public static void main(String[] args) {
    double num = 21.3498534263;

    System.out.format("%.2f", num);
  }
}
Output
21.35

Java Program to Round a Decimal Number using DecimalFormat Class

The DecimalFormat class, a subclass of NumberFormat, is used in Java to format decimal integers. The format is declared using the # patterns (like #.###), where the number of # after the decimal point represents the number of digits we want to print. By default, the number is rounded off to the ceiling value itself. For Example, if 5.456789 is rounded to 3 decimal places using #.### format then it will prints 5.457.

import java.text.DecimalFormat;

public class RoundNumberDecimalFormat {
  public static void main(String[] args) {
    double num = 2.123456;
    DecimalFormat df = new DecimalFormat("#.###");
    System.out.println(df.format(num));
  }
}
Output
2.123