1、返回 String 类型数据code
对数据进行处理后,返回 String 类型数据,能够经过以下方式进行处理:orm
二者达到的效果是同样的。ci
- 小数点后位数不足的,补0 - 四舍五入,对数据截断
Double d = 123.451789D; DecimalFormat decimalFormat = new DecimalFormat("#.0000000"); DecimalFormat decimalFormat2 = new DecimalFormat("#.000"); DecimalFormat decimalFormat3 = new DecimalFormat("#.00"); //补齐位数 System.out.println(decimalFormat.format(d)); //四舍五入 System.out.println(decimalFormat2.format(d)); System.out.println(decimalFormat3.format(d)); //四舍五入 System.out.println(String.format("%.2f",d)); System.out.println(String.format("%.3f",d)); //补齐位数 System.out.println(String.format("%.10f",d));
补充:io
String.format 中对数字处理有以下限制: %[argument_index$][flags][width][.precision][t]conversionform
2、返回 Double 类型数据方法
可经过 BigDecimal 对数据进行处理,在精度的处理上能知足多种需求:im
System.out.println(BigDecimal.valueOf(d).setScale(2, BigDecimal.ROUND_UP).doubleValue()); System.out.println(BigDecimal.valueOf(d).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue()); System.out.println(BigDecimal.valueOf(d).setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue());