zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    进程线程协程
    面向对象完善总结
    面向对象编程
    常用模块2
    python常用模块
    随机验证码模块(random)
    带有key参数的函数filter,map,max,min
    python内置函数、匿名函数、递归
    python迭代器与生成器
    如何添加title左侧的图标
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744374.html
Copyright © 2011-2022 走看看