You can set Precision for double value either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.
1. Setting double precision using DecimalFormat
DecimalFormatExample.java
package com.codersarts;
import java.text.DecimalFormat;
public class DecimalFormatExample {
// setting precision upto 2 decimal point
private static DecimalFormat df = new DecimalFormat("#.##");
public static void main(String[] args) {
double piValue = 3.14159265359;
System.out.println("double : " + piValue);
System.out.println("double : " + df.format(piValue)); //3.14
}
}
Output
double : 3.14159265359
double : 3.14
2. Setting double precision using BigDecimal
//BigDecimalFormatExample.java
package com.codersarts;
import java.math.RoundingMode;
import java.math.BigDecimal;
public class BigDecimalFormatExample {
public static void main(String[] args) {
double piValue = 3.14159265359;
System.out.println("double : " + piValue);
BigDecimal bd = new BigDecimal(piValue).setScale(2, RoundingMode.HALF_UP);
double newInput = bd.doubleValue();
System.out.println("double : " + newInput);
}
}
3. Setting double precision using String.format
package com.codersarts;
public class StringFormatExample {
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + String.format("%.2f", input));
System.out.format("double : %.2f", input);
}
}
Note: You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.