Thursday, June 4, 2009

java BigDecimal problem

BigDecimal v = new BigDecimal(0.12d);
System.out.println(v);

result: 0.11999999999999999555910790149937383830547332763671875

Because ::: In Java API

public BigDecimal(double val)

Translates a double into a BigDecimal. The scale of the BigDecimal is the smallest value such that (10scale * val) is an integer.

Note: the results of this constructor can be somewhat unpredictable.

---

But ...


BigDecimal v = new BigDecimal("0.12");
System.out.println(v);

result: 0.12

Because:

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.

ref: http://www.narisa.com/forums/index.php?showtopic=12589&st=15

No comments:

Post a Comment