BigDecimal adding wrong value
Use a String literal:
private static final BigDecimal sd = new BigDecimal("0.7");
If you use a double
, actually public BigDecimal(double val)
is called. The reason you do not get 0.7 is that it cannot be exactly represented by a double
. See the linked JavaDoc for more information.
Perhaps if you bothered to read the documentation, i.e. the javadoc of the constructor you're using, you'd already know the answer.
- When a
double
must be used as a source for aBigDecimal
, note that this constructor provides an exact conversion; it does not give the same result as converting thedouble
to aString
using theDouble.toString(double)
method and then using theBigDecimal(String)
constructor. To get that result, use thestatic
valueOf(double)
method.
When you then look at the javadoc of BigDecimal.valueOf(double)
, you'll find:
Note: This is generally the preferred way to convert a
double
(orfloat
) into aBigDecimal
, as the value returned is equal to that resulting from constructing aBigDecimal
from the result of usingDouble.toString(double)
.
So there is your answer: Use BigDecimal.valueOf(0.7d)
, not new BigDecimal(0.7d)
.