Thursday, June 4, 2009

java BigDecimal problem

BigDecimal v = new BigDecimal(0.12d);

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");

result: 0.12


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.


No comments:

Post a Comment