Round a Number to n Decimal Places in Java

Exercise:

Write a Java Program to round a number to n decimal places.

1.Round using format

Click Here to View the Solution!
public class RoundDecimal {
  
     public static void main(String[] args) {
         double num = 2.98765;
         //Declaring to round up to 5 decimal places 
         System.out.format("%.5f", num);
     }
 } 
Click Here to View the Output!
2.98765
Click Here to View the Explanation!
  • This program is used to round a number (num) to a number n of decimal places by using a Java method format().
  • A number, of the data type double is initialized as num = 2.98765112. This is the number which is to be rounded to a specific number of decimal places.
  • The Java format() method is used that prints a floating-point number up to the 4 decimal places. The number of decimal places are specified by using the format: (.5f).
  • The phrase “up to 5 decimal places” means to print 5 digits after the decimal point in a number. And the f in the format represents the floating-point number

2.Round using decimal format

Click Here to View the Solution!
import java.math.RoundingMode;
import java.text.DecimalFormat;
 
public class RoundDecimal {
 
    public static void main(String[] args) {
        double num = 2.987654321;
        DecimalFormat df = new DecimalFormat("#.####");
        df.setRoundingMode(RoundingMode.CEILING);
        System.out.println(df.format(num));
    }
} 
Click Here to View the Output!
2.9877
Click Here to View the Explanation!
  • This program is used to round a given number up to the n number of decimal places by using a class DecimalFormat of the java.text package and class RoundingMode of the package java.math.
  • A number, of the data type double is initialized as num = 2.987654321. This is the number which is to be rounded to a specific number of decimal places.
  • The DecimalFormat class in the program is used to round the number by creating its object. This object will hold the format (#.####) of how num is to be presented (up to 3 decimal places).
  • Also, the RoundingMode method ceiling is used to round the last digit place of num to its next possible number.
  • As a result, the num (2.987654321) is rounded up to 4 decimal places and it last place digit ‘6’is rounded to its next number ‘7’. Hence, the output that will be printed is 2.9877
%d bloggers like this: