我有个事例,您能可以参考下。和你说的差不多。
Double db = 1.06D;
System.out.println(db+"="+db);
BigDecimal big = BigDecimal.valueOf(db);
System.out.println(db+"="+big);
BigDecimal big2 = new BigDecimal(db);
System.out.println(db+"="+big2);
结果是
1.06=1.06
1.06=1.06
1.06=1.060000000000000053290705182007513940334320068359375
float和double只能用来做科学计算或者是工程计算,在商业计算中我们要用 java.math.BigDecimal
BigDecimal(double val) 这个构造函数有如下说明:
Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding.
The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.
原来我们如果需要精确计算,非要用String来够造BigDecimal不可!在《Effective Java》一书中的例子是用String来够造BigDecimal的,但是书上却没有强调这一点,这也许是一个小小的失误吧。
解决方案
现在我们已经可以解决这个问题了,原则是使用BigDecimal并且一定要用String来够造。 |