工作时,有人用new BigDecmal (double)的方式计算精确数值,发现会有精度缺失的问题,改用BigDecimal.valueOf(double)的方式便好了,于是看了下两个源码。
1、new BigDecmal (double)源码
在传入double的时候,没有经过先转为string再进行转换,会有精度缺失的问题,源码的注释上也注明了这一点,追求精度的用valueOf方法或是可先将double 转为String然后用new BigDecmal (string)
/**
* Translates a {@code double} into a {@code BigDecimal} which
* is the exact decimal representation of the {@code double}'s
* binary floating-point value. The scale of the returned
* {@code BigDecimal} is the smallest value such that
* <tt>(10<sup>scale</sup> × val)</tt> is an integer.
* <p>
* <b>Notes:</b>
* <ol>
* <li>
* The results of this constructor can be somewhat unpredictable.
* One might assume that writing {@code new BigDecimal(0.1)} in
* Java creates a {&#