I’ve a variable price which is defined this way:
double price;
price = 7.6;
Up to here everything is right. The problem is that when I make this:
price = 7.6 * 3;
What i get is
price = 22.799999999999999999999999997
instead of
price = 22.80
which is what i need.
Any ideas about how to solve this?? Thank you.
Use
BigDecimalor store your amounts of money in cents and uselong.For reasons read Effective Java Item 48.
In summary:
Don’t use
doubleandfloatwhen you need exact values. These datatypes cannot represent numbers wich are a negative power of ten. (e.g. 0.1)Use
BigDecimalinstead. For monetary valueslongorintare more suitable in most cases.Your example using long: