方式一:保留两位小数
DecimalFormat df = new DecimalFormat("#.00");
double d1 = 1.23456
double d2 = 2.0;
double d3 = 0.0;
System.out.println(df.format(d1),df.format(d2),df.format(d3));
输出结果:1.23 2.00 0.00
方式二:保留两位小数并四舍五入
①
public class TwoDecimal {
public static void main(String[] args) {
final double d = 23.456;
//double类型转换为String形式
String f = Double.toString(d);
BigDecimal bigDecimal = new BigDecimal(f);
// 这里的 2 就是你要保留的小数位数。
double f1 = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("保留两位小数 : " + f1);
}
}
输出结果:保留两位小数 : 23.46
②
public class qq {
public static void main(String[] args) {
double i = 23.546;
NumberFormat nf = NumberFormat.getNumberInstance();
// 2是显示的小数点后的显示的最多位,显示的最后位是舍入的
nf.setMaximumFractionDigits(2);
String result = nf.format(i);
System.out.print("结果是:"+result);
}
}
输出结果:结果是 :23.55