保留指定小数位数或四舍五入

 double f = 3.1516;
 BigDecimal b = new BigDecimal(f);
 double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();  //BigDecimal.ROUND_HALF_UP 属性含义为为四舍五入
输出结果f1为 3.15;

2、

String format = new DecimalFormat("#.0000").format(3.1415926);

System.out.println(format); 输出结果为 3.1416

3、

double num = 3.1415926;
String result = String.format("%.4f", num);//%.2f 中 %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型
System.out.println(result);
输出结果为:3.1416

4、

double num = Math.round(5.2544555 * 100) * 0.01d; //0.01d表示小数点后保留的位数(四舍五入)
System.out.println(num);

猜你喜欢

转载自www.cnblogs.com/chengshixiaonongming/p/10410840.html
今日推荐