“new BigDecimal(13.3D)” results in imprecise “13.3000000000000007105..”?

前端 未结 5 1305
栀梦
栀梦 2020-12-05 15:06

How is it that Java\'s BigDecimal can be this painful?

Double d = 13.3D;

BigDecimal bd1 = new BigDecimal(d);
BigDecimal bd2 = new BigDecimal(St         


        
5条回答
  •  無奈伤痛
    2020-12-05 15:48

    Your problem has nothing to do with BigDecimal, and everything with Double, which cannot represent 13.3 accurately, since it uses binary fractions internally.

    So your error is introduced in the very first line. The first BigDecimal simply preserves it, while String.valueOf() does some fishy rounding that causes the second one to have the desired content, pretty much through luck.

提交回复
热议问题