How to set Precision for Double values in Java?

Given a double value val, the task is to set its precision value to a specific decimal places. 

Examples: 
 

Input: val = 1 
Output: 1.0000
Upto 4 decimal places

Input : 12.5
Output : 12.500000
Upto 6 decimal places

 

 

Approach: Using String.format() 



We can use String.format() method to format the decimal number to some specific format.

Syntax:

String.format("%.Df", decimalValue);

where D is the number required number of Decimal places.

 

Below is the implementation of the above approach:

 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.io.*;
import java.lang.*;
  
class GFG {
  public static void main(String[] args) {
  
    double a = 0.9;
  
    // Setting the precision to 20 places
    System.out.println(
      String.format("%.20f", a));
  
    double b = 1;
  
    // Setting the precision to 5 places
    System.out.println(
      String.format("%.5f", b));
  }
}

chevron_right


Output: 

0.99999999999999990000
1.00000

 

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.