Hi, I'm writing a simple program that runs a vending machine. I thought I had everything working fine untill I messed around with the money input some more. In my program I obviously compare money values and check to make sure the values match up exactly to buy an item. It works under almost every case, but I have found some cases where I get an anomalous decimal value that throws off the comparison of the double values. Here is my code and output from testing within the money class itself.
public class Money {
private static final double NICKEL_AMMNT = 0.05;
private static final double DIME_AMMNT = 0.10;
private static final double QRT_AMMNT = 0.25;
private int numNickels, numDimes, numQrts;
public Money(int numNickels, int numDimes, int numQrts) {
this.numNickels = numNickels;
this.numDimes = numDimes ;
this.numQrts = numQrts ;
}
public int getNickels(){
return numNickels;
}
public int getDimes(){
return numDimes;
}
public int getQrts(){
return numQrts;
}
public double getTotal(){
double total = ((numNickels * NICKEL_AMMNT) + (numDimes * DIME_AMMNT) + (numQrts * QRT_AMMNT));
return total;
}
public String toString(){
String tempString = "";
tempString += ("Nickels: "+getNickels()+"\n");
tempString += ("Dimes: "+getDimes()+"\n");
tempString += ("Quarters: "+getQrts()+"\n");
tempString += ("Total Cash: $"+(getNickels()*NICKEL_AMMNT + getDimes()*DIME_AMMNT + getQrts()*QRT_AMMNT));
return tempString;
}
public static void main(String[] args){
Money money1 = new Money(2, 3, 1);
System.out.println("2 Nickels, 3 Dimes, 1 Quarter");
System.out.println(money1.getTotal()+"\n");
Money money2 = new Money(3, 2, 3);
System.out.println("3 Nickels, 2 Dimes, 3 Quarters");
System.out.println(money2.getTotal()+"\n");
Money money3 = new Money(1,6,0);
System.out.println("1 Nickels, 6 Dimes, 0 Quarters\n"+money3.getTotal());
Money money4 = new Money(3,0,0);
System.out.println("\n3 Nickels,0 Dimes, 0 Quarters\n"
+money4.getTotal());
}
}
The output from this code in main gives me:
2 Nickels, 3 Dimes, 1 Quarter
0.65
3 Nickels, 2 Dimes, 3 Quarters
1.1
1 Nickels, 6 Dimes, 0 Quarters
0.6500000000000001
3 Nickels,0 Dimes, 0 Quarters
0.15000000000000002
It works fine under most cases, but I'm sometimes getting weird results when adding up the values. Can someone explain first why this is occuring, and how to fix it, or foce my double values to be two decimal places?