This is due to the limited precision in doubles.
The root of your problem is that the literal 123.55
actually represents the value 123.54999...
.
It may seem like it holds the value 123.55
if you print it:
System.out.println(123.55); // prints 123.55
but in fact, the printed value is an approximation. This can be revealed by creating a BigDecimal
out of it, (which provides arbitrary precision) and print the BigDecimal:
System.out.println(new BigDecimal(123.55)); // prints 123.54999999999999715...
You can solve it by going via Math.round
but you would have to know how many decimals the source double actually entails, or you could choose to go through the string representation of the double in fact goes through a fairly intricate algorithm.
If you're working with currencies, I strongly suggest you either
- Let prices etc be represented by
BigDecimal
which allows you to store numbers as 0.1
accurately, or
- Let an
int
store the number of cents (as opposed to having a double store the number of dollars).
Both ways are perfectly acceptable and used in practice.