java中关于BigDecimal用法的思考

public static void main(String[] args) {
    double num1 = 30.0000000000000003;
    System.out.println(num1 == 30);

    BigDecimal bigNum1 = new BigDecimal(new Double(num1).toString());
    BigDecimal bigNum2 = new BigDecimal(new Double(num1));
    System.out.println(bigNum1.equals(30));
    System.out.println(bigNum2.equals(30));

    System.out.println("-----------------------------");
    // BigDecimal的构造函数 public BigDecimal(double val) 损失了double 参数的精度
    // 一些资料中提到使用字符串来构建BigDecimal更加精确,通过以下示例发现确实有效
    double d = 301353.05;
    BigDecimal bigNum3 = new BigDecimal(d);
    System.out.println(bigNum3);//301353.0499999999883584678173065185546875
    BigDecimal bigNum4 = new BigDecimal(new Double(d).toString());
    System.out.println(bigNum4);
//        System.out.println(decimal.setScale(1, RoundingMode.HALF_UP));//301353.0

    System.out.println("-----------------------------");
    // 然而Double的toString()方法并不是一个精确的方法
    // 其输出的字符串为一个接近的值
    d = 301353.0499999999883584678173065185546875d;
    System.out.println(d);
    System.out.println(new Double(d).toString());
    System.out.println(new Double(d).toString());
    System.out.println(new BigDecimal(d));
}

输出:

true
false
false
-----------------------------
301353.0499999999883584678173065185546875
301353.05
-----------------------------
301353.05
301353.05
301353.05
301353.0499999999883584678173065185546875
posted @ 2019-08-28 17:11  点点爱梦  阅读(217)  评论(0编辑  收藏  举报