As the previous answers stated, this is a consequence of doing floating point arithmetic.
As a previous poster suggested, When you are doing numeric calculations, use java.math.BigDecimal
.
However, there is a gotcha to using BigDecimal
. When you are converting from the double value to a BigDecimal
, you have a choice of using a new BigDecimal(double)
constructor or the BigDecimal.valueOf(double)
static factory method. Use the static factory method.
The double constructor converts the entire precision of the double
to a BigDecimal
while the static factory effectively converts it to a String
, then converts that to a BigDecimal
.
This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the BigDecimal
constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.
double value = 0.585;
System.out.println(new BigDecimal(value));
System.out.println(BigDecimal.valueOf(value));
on my system gives
0.58499999999999996447286321199499070644378662109375
0.585