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)); } } |
0.99999999999999990000 1.00000
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- BigDecimal precision() Method in Java
- Java Guava | Doubles.indexOf(double[] array, double target) method with Examples
- Java Guava | Doubles.indexOf(double[] array, double[] target) method with Examples
- Java.Lang.Double class in Java
- Double Brace Initialization in Java
- Comparison of double and float primitive types in Java
- DoubleStream reduce(double identity, DoubleBinaryOperator op) in Java with Examples
- Double byteValue() Method in Java with Examples
- Double.compareTo() Method in Java with Examples
- Double.equals() Method in Java with Examples
- DoubleStream.Builder add(double t) in Java with Examples
- Double doubleValue() method in Java with examples
- Double intValue() method in Java with examples
- Double shortValue() method in Java with examples
- Double floatValue() in Java with Examples
- Double longValue() in Java with Examples
- Double hashCode() method in Java with examples
- Double compare() Method in Java with Examples
- Double isInfinite() method in Java with examples
- Double doubleToLongBits() method in Java with examples
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.

