You can't. Doubles don't have a format or a number of places after then decimal. All you can do is format it use java.text.DecimalFormat or String.format, or if you want fixed decimal precision, use BigDecimal.
Yep, BigDecimal seems to be what you want. There is a time cost when using BigDecimal though, so keep that in mind if you do decide to use BigDecimal.
Example code:
package tester;
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
new BigDecimalExample();
}
private BigDecimalExample() {
double piDouble = 22/7.0;
System.out.println("piDouble: "+piDouble);
BigDecimal piTo2DecimalPlaces = new BigDecimal(piDouble);
piTo2DecimalPlaces = piTo2DecimalPlaces.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("piTo2DecimalPlaces: "+piTo2DecimalPlaces.doubleValue());
}
}
Program output:
piDouble: 3.142857142857143
piTo2DecimalPlaces: 3.14