关于BigDecmal精度缺失的问题

今天在项目中遇到一个奇怪的现象

Double doubleValue = new BigDecimal("0.02").subtract(new BigDecimal(0.02)).doubleValue();

预计出现的结果是0.0

可是通过打印出现的结果是-4.163336342344337E-19

在网上找了很多资料,都是说BigDecimal的构造建议用string,自己也试了下利用string构造也不会出问题

最后在double参数的构造上看到这一段注释:
     The results of this constructor can be somewhat unpredictable.
     * One might assume that writing {@code new BigDecimal(0.1)} in
     * Java creates a {@code BigDecimal} which is exactly equal to
     * 0.1 (an unscaled value of 1, with a scale of 1), but it is
     * actually equal to
     * 0.1000000000000000055511151231257827021181583404541015625.
     * This is because 0.1 cannot be represented exactly as a
     * {@code double} (or, for that matter, as a binary fraction of
     * any finite length).  Thus, the value that is being passed
     * <i>in</i> to the constructor is not exactly equal to 0.1,
     * appearances notwithstanding.

大概的意识就是说double会出现精度缺失,不建议使用!所以以后还是用String吧

猜你喜欢

转载自blog.csdn.net/weixin_39982274/article/details/82426381