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
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
filter_none
Output:
0.99999999999999990000 1.00000
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.