第一种方法:
double f = 123.2315455458;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue(); //保留3位小数,最后一位四舍五入
System.out.println(f1);
输出为:123.232
第二种方法:
DecimalFormat df = new DecimalFormat("#.000"); //#.000保留三位小数,依次类推
String f = df.format(123.2315452); //四舍五入
System.out.println(f);
输出为:123.232
第三种方法:
double d = 123.2315455458;
String s = String.format("%.6f", d); //保留6位小数,最后一位四舍五入
System.out.println(s);
输出为:123.231546
%. 表示小数点前任意位数 6 表示两位小数 格式后的结果为 f 表示浮点型
转载于:https://www.cnblogs.com/silence-x/p/11302275.html