• BigDecimal


    例子:加减乘除(+-*/)

    System.out.println(0.05 + 0.01);
    System.out.println(1.0 - 0.42);
    System.out.println(4.015 * 100);
    System.out.println(123.3 / 100);
    

     运算结果:

    0.060000000000000005
    0.5800000000000001
    401.49999999999994
    1.2329999999999999

    关于BigDecimal丢失精度的问题,声明BigDecimal对象的时候一定要使用它构造参数为String的类型的构造器

    BigDecimal a1 = new BigDecimal(Double.toString(0.05));
    BigDecimal a2 = new BigDecimal(Double.toString(0.01));
    System.out.println(a1.add(a2));
    BigDecimal b1 = new BigDecimal(Double.toString(1.0));
    BigDecimal b2 = new BigDecimal(Double.toString(0.42));
    System.out.println(b1.subtract(b2));
    BigDecimal c1 = new BigDecimal(Double.toString(4.015));
    BigDecimal c2 = new BigDecimal(Double.toString(100));
    System.out.println(c1.multiply(c2));
    BigDecimal d1 = new BigDecimal(Double.toString(123.3));
    BigDecimal d2 = new BigDecimal(Double.toString(100));
    System.out.println(d1.divide(d2, 2, BigDecimal.ROUND_HALF_UP));//应对除不尽的情况, 2 = 保留小数点后两位   ROUND_HALF_UP = 四舍五入

    运算结果:

    0.06
    0.58
    401.5000
    1.23
    

      

  • 相关阅读:
    挺好的程序员面试网址
    [转]浅谈协方差矩阵
    坚持
    matlab中文论坛
    看书
    Opengl绘制点
    说服力
    心情
    vector操作
    我的毕设
  • 原文地址:https://www.cnblogs.com/zxg-6/p/12969415.html
Copyright © 2020-2023  润新知