Don't use float or double for any calculations that require an exact answer.
The float and double types are particularly ill-suited for monetary calculations
because it is impossible to represent 0.1(or any other negative power of ten) as a float or double exactly.
Use BigDecimal, int or long for monetary calculations.
Use BigDecimal if you want the system to keep track of the decimal point and you don't mind the inconvenience of not using a primitive type.
If performance is of the essence, if you don't mind keeping track of the decimal point yourself, and if the quantities aren't too big, use int or long.
If the quantities don't exceed nine decimal digits, you can use int.
If they don't exceed eighteen digits, you can use long.
If the quantities exceed eighteen digits, you must use BigDecimal.
Here is an example:
import java.math.BigDecimal;
public class Test1 {
public static void main(String args[]) {
System.out.println("method test1() executed!");
test1();
System.out.println("method test2() executed!");
test2();
System.out.println("method test3() executed!");
test3();
}
public static void test1() {
double funds = 1.00;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + " itmes bought.");
System.out.println("Change: $" + funds);
}
public static void test2(){
final BigDecimal TEN_CENTS = new BigDecimal(".10");
int itemsBought = 0;
BigDecimal funds = new BigDecimal("1.00");
for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0; price = price.add(TEN_CENTS)){
itemsBought++;
funds = funds.subtract(price);
}
System.out.println(itemsBought + " itmes bought.");
System.out.println("Change: $" + funds);
}
public static void test3() {
int itemsBought = 0;
int funds = 100;
for (int price = 10; funds >= price; price += 10) {
itemsBought++;
funds -= price;
}
System.out.println(itemsBought + " items bought." );
System.out.println("Money left over: " + funds + " cents");
}
}
Result:
method test1() executed!
3 itmes bought.
Change: $0.3999999999999999
method test2() executed!
4 itmes bought.
Change: $0.00
method test3() executed!
4 items bought.
Money left over: 0 cents
Comment:
the result of test1() is the Wrong answer!