Float转BigDecimal失精度

类似于new BigDecimal(3.1F) 或者BigDecimal.valueOf(3.1F)会失掉精度,应该选用new BigDecimal(Float.toString(3.1F))等方式。原因参考:https://docs.oracle.com/javase/10/docs/api/java/math/BigDecimal.html#%3Cinit%3E(double)

1,The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a 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 double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

2,The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

3, When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

1, 该构造函数的接口可能是非预期的。一般会认为new BigDecimal(0.1)的值应该绝对等于0.1,但实际上是0.1000000000000000055511151231257827021181583404541015625。这是因为0.1不能用double精确的表达,真正传递给构造函数的值并不是精确的0.1。

2,String构造函数却可完美预期,new BigDecimal("0.1")会得到精确值。因此通常建议使用String构造函数。

3, 如果必须用double作为BigDecimal的原始数据,应注意该构造函数会做额外转化;所得的值和把double转成String在通过String构造函数所得值不同。要获得String构造函数所得值需要通过静态的valueOf(double)方法。

需要注意BigDecimal.valueOf(3.1F)虽然调用了valueOf(double)方法,但是在float转double的时候就已经失真了。

转载于:https://my.oschina.net/u/3731752/blog/1841075

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值