關於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吧