代码:
public class Test {
public static void main(String[] args) {
double num = 756.2345566;
//方法一:最简便的方法,调用DecimalFormat类
DecimalFormat a = new DecimalFormat("#.00");
System.out.println(a.format(num));
//方法二:直接通过String类的format函数实现
System.out.println(String.format("%.2f", num));
//方法三:通过BigDecimal类实现
BigDecimal b = new BigDecimal(num);
double c = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(c);
//方法四:通过NumberFormat类实现
NumberFormat d = NumberFormat.getNumberInstance();
d.setMaximumFractionDigits(2);
System.out.println(d.format(num));
}
}
结果:
756.23
756.23
756.23
756.23