JAVA 的BigDecimal 与Double的区别

王铎开 2011-12-26 04:45:54
1) 8.459669791666667.multiply(4800).doubleValue()
b1.multiply(b2)
(java.math.BigDecimal) 40606.4149999999968000
b1.multiply(b2).doubleValue()
(double) 40606.41499999999

2) 8.459669791666667*4800=40606.415

用BigDecimal的multiply(第一种方法)算出的结果40606.4149999999968000 。保留两位是40606.41
用普通的(*)乘法(第二种方法)来计算就是40606.415。保留两位是40606.42,这样结果就相差0.01。
但我觉得跟这个没关系,默认会四舍五入的。
应该是doubleValue的问题。

怎么BigDecimal会丢失精度呢?求解。。。


...全文
882 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
teemai 2011-12-26
  • 打赏
  • 举报
回复
请看jdk:

doubleValue
public double doubleValue()
Converts this BigDecimal to a double. This conversion is similar to the narrowing primitive conversion from double to float as defined in the Java Language Specification: if this BigDecimal has too great a magnitude represent as a double, it will be converted to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of the BigDecimal value.

Specified by:
doubleValue in class Number
Returns:
this BigDecimal converted to a double.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧