Skip to content
Related Articles

Related Articles

Improve Article

How to set Precision for Double values in Java?

  • Difficulty Level : Medium
  • Last Updated : 13 May, 2021
Geek Week

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

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.


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

where D is the number required number of Decimal places.

Below is the implementation of the above approach:


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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :