对 java 数字小数点后位数进行处理

一、返回 String 类型数据

对数据进行处理后,返回 String 类型数据,可以通过如下方式进行处理:

  • DecimalFormat 对数据格式化
  • String.format 对数据格式化

两者达到的效果是一样的。

- 小数点后位数不足的,补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));

补充:

String.format 中对数字处理有如下限制: %[argument_index$][flags][width][.precision][t]conversion

二、返回 Double 类型数据

可通过 BigDecimal 对数据进行处理,在精度的处理上能满足多种需求:

  • BigDecimal.setScale()方法用于格式化小数点
  • setScale(1)表示保留一位小数,默认用四舍五入方式
  • setScale(1,BigDecimal.ROUND_DOWN) 直接删除多余的小数位,如2.35会变成2.3
  • setScale(1,BigDecimal.ROUND_UP) 进位处理,2.35变成2.4
  • setScale(1,BigDecimal.ROUND_HALF_UP) 四舍五入,>=0.5时向上取,反之则向下
  • setScaler(1,BigDecimal.ROUND_HALF_DOWN)四舍五入,>0.5时向上取,反之则向下
    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());

猜你喜欢

转载自my.oschina.net/pding/blog/1815188