java去除数字末尾0,整数去除.0,浮点型保留精度

  • Post author:
  • Post category:java


/**
     * 去除double类型后多余的 0
     * @param num
     * @return
     */
    public static Double noZeros(Double num) {
        BigDecimal value = new BigDecimal(num);
        //去除多余0
        BigDecimal noZeros = value.stripTrailingZeros();
        //BigDecimal => double
        return noZeros.doubleValue();
    }

    public static String doubleTrans(double d){
        double eps = 1e-10;
        //判断是否为整数
        if(d-Math.floor(d) < eps){
            return String.valueOf((long)d);
        }
        DecimalFormat df = new DecimalFormat("#.#####");
        return df.format(d);
    }

测试

    public static void main(String[] args) {
        Double[] dArray = new Double[]{1d,1.2d, 3.1415926d, 1.001d, 2.00d, 6.4567890d, 10001.20002d, 20032.780d, 234.900d};
        for (Double d : dArray)
            System.out.println("对比:" + d + " | " +  doubleTrans(noZeros(d)));
    }

输出

对比:1.0 | 1
对比:1.2 | 1.2
对比:3.1415926 | 3.14159
对比:1.001 | 1.001
对比:2.0 | 2
对比:6.456789 | 6.45679
对比:10001.20002 | 10001.20002
对比:20032.78 | 20032.78
对比:234.9 | 234.9



版权声明:本文为as350144原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。