BigDecimal的问题

来源:互联网 发布:天涯论坛和知乎 编辑:程序博客网 时间:2024/06/06 01:11

Java Doc解释


public BigDecimal(doubleval)Translatesa double into a BigDecimal which is the exact decimal representation of thedouble's binary floating-point value. The scale of the returned BigDecimal isthe smallest value such that (10scale × val) is an integer.

Notes:

The results of this constructor can besomewhat unpredictable. One might assume that writing new BigDecimal(0.1) inJava creates a BigDecimal which is exactly equal to 0.1 (an unscaledvalue of 1, with a scale of 1), but it is actually equal to0.1000000000000000055511151231257827021181583404541015625. This is because 0.1cannot be represented exactly as a double (or, for that matter, as a binaryfraction of any finite length). Thus, the value that is being passed in to theconstructor is not exactly equal to 0.1, appearances notwithstanding.

The String constructor, on the otherhand, is perfectly predictable: writing new BigDecimal("0.1") createsa BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, itis generally recommended that the String constructor be used in preference tothis one.

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



案例:

// float / double不能表示精确的小数。System.out.println(0.01 + 0.09); // 0.09999999999999999System.out.println(1.0 / 3 * 3);// BigDecimalBigDecimal bd1 = new BigDecimal(0.09);BigDecimal bd2 = new BigDecimal(0.01);System.out.println(bd1.add(bd2));  // 0.09999999999999999687749774324174723005853593349456787109375

BigDecimal bd3 = new BigDecimal("0.09");BigDecimal bd4 = new BigDecimal("0.01");System.out.println(bd3.add(bd4));  // 0.1


原创粉丝点击