关于Java计算精度问题

初级问题:

double i = 399 * 0.075;

此时结果:29.924999999999997 明显和我们应得的29.925有精度上的问题

so,马上想到了BigDecimal这一高精度计算专用的类

new BigDecimal(399).multiply(new BigDecimal(0.075)).doubleValue();

此时结果:29.924999999999997,说好的高精度计算呢
后发现
Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding. The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(“.1”) is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

即构造参数传入double时奇数转换二进制还是存在精度问题,而string就完全ok

最终

`new BigDecimal(399).multiply(new BigDecimal("0.075")).doubleValue();

得到预知结果

    原文作者:我的天呐0_0
    原文地址: https://www.jianshu.com/p/c88155234b67
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞