BigDecimal使用注意

来源:互联网 发布:微信ubuntu版 编辑:程序博客网 时间:2024/05/16 07:15

今天摸着API试验了BigDecimal类,都不是特别理想,实验过程:

浮点数的不精确是广泛存在的。在java中的Math包中有一个BigDecmal类专门用来处理大精度数据。

The BigDecimal class provides operations for arithmetic, scalemanipulation, rounding, comparison, hashing, and format conversion.The toString() method provides a canonical representation of aBigDecimal.


double a = 5.899989871234567890987654321;
System.out.println(a); //输出结果:5.899989871234568

BigDecimal bd = newBigDecimal(5.899989871234567890987654321);
System.out.println(bd);//输出结果:5.89998987123456775094609838561154901981353759765625

MathContext mc = new MathContext(28);
BigDecimal bd = new BigDecimal(5.899989871234567890987654321,mc);
System.out.println(bd);//输出结果:5.899989871234567750946098392

百度了下看了下其他人的blog才明白原来要用String作为形参构造,才能得到最精确的结果。如下:

MathContext mc = new MathContext(28);
BigDecimal bd = new BigDecimal("5.899989871234567890987654321",mc);
 System.out.println(bd);//输出结果:5.899989871234567890987654321

Note: the results of this constructor can be somewhatunpredictable. One might assume that new BigDecimal(.1) is exactlyequal to .1, but it is actually equal to.1000000000000000055511151231257827021181583404541015625. This isso because .1 cannot be represented exactly as a double (or, forthat matter, as a binary fraction of any finite length). Thus, thelong value that is being passed in to the constructor is notexactly equal to .1, appearances nonwithstanding.
The (String) constructor, on the other hand, is perfectlypredictable: new BigDecimal(".1") is exactly equal to .1, as onewould expect. Therefore, it is generally recommended that the(String) constructor be used in preference to this one.

嗯,note一记!