You should never use a double
or any other floating-point data type to represent money. The reason is that they can't represent all values exactly. For example, the following line:
System.out.println(new BigDecimal(0.1));
prints
0.1000000000000000055511151231257827021181583404541015625
For a longer explanation why, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.
I suggest using BigDecimal
instead.
An alternative if you only want to use primitives is to use an int
to store the currency value in cents instead, and divide by 100 when displaying the value.