Round a double to 2 decimal places in java

In this tutorial, we will learn how to round a double to 2 decimal places in Java. We can round a number by using the following methods:

  • using String.format()
  • using printf()

By using String.format function

Also Read:

How to use String.format function in java

import java.util.*;
public class RoundingUsingStringFormat {
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a double number:");
    double a1=sc.nextDouble();
    String t1=String.format("%.2f",a1);
    System.out.println(t1);
    }
}

Here, I have taken input from the user then I have initialized a String and by using the String.format function which is rounding off a double number to 2 decimal digits.

The output looks like this:

Enter a double number:
4.5567
4.56

By using printf for formatting

import java.util.*;
public class RoundingUsingPrintf {
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a double number:");
    double a1=sc.nextDouble();
    System.out.printf("%.2f",a1);
    }
}  

Here, I have taken input from a user, then for formatting, I have used printf.

The output looks like this:

Enter a double number:
3.4556
3.46

Leave a Reply

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