java

How to round a number to n decimal places in Java

In this tutorial, we are going to see how to round a number to n decimal places in Java using two different methods.

  • Using System.out.format()
  • Using Math.round()

 

Method 1: How to round a number to n decimal places using System.out.format()
public class Main {
    public static void main(String[] args) {
        double nbr = 5.917856;
        System.out.format("%.2f", nbr);
    }
}

Output:

5.92

 

 
In the above code, we have used the format() method to display the given number to 2 decimal places. The 2 decimal places are given by the .2f format.
 

Method 2: How to round a number to n decimal places using Math.round()
public class Main {

    public static void main(String[] args) {
        double nbr = 5.917856;
        double res = Math.round(nbr * 100.0) / 100.0;
        System.out.print(res);
    }
}

Output:

5.92
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *