Edit: A possible solution: I tried to print remaining and I got this: 3.75 1.75 0.75 0.25 0.049999997 0.029999997 0.009999998
0.04 and 0.02 I guess are the issues!
My Qustion:
I Have to write a cash register program in java in-which I did the register have only the following notes:
- One Franc: .01
- Two Franc: .02
- Five Franc: .05
- Ten Franc: .10
- Twenty Franc: .20
- Fifty Franc: .50
- One centime: 1
- Two centimes: 2
- Five centimes: 5
- Ten centimes: 10
- Twenty centimes: 20
- Fifty centimes: 50
so for example:
input:
price = 11.25
cash = 20
output:
Five Francs, Two Francs, One Franc, Fifty Centimes, Twenty Centimes, Five Centimes
my problem is that my code gives me this output instead:
Five Francs, Teo Francs, One Franc, Fifty Centimes, Twenty Centimes, Two Centimes, Two Centimes
Notice how instead of Five Centimes I get 2 of Two Centimes so I'm 1 Centime Short.
I solved it using a simple loop & Enum here it's:
My Enum:
public enum bill {
Fifty_Francs( 50.00f),
Twenty_Francs( 20.00f),
Ten_Francs( 10.00f),
Five_Francs( 5.00f),
Teo_Francs( 2.00f),
One_Franc( 1.00f),
Fifty_Centimes( 0.50f),
Twenty_Centimes( 0.20f),
Ten_Centimes( 0.10f),
Five_Centimes( 0.05f),
Two_Centimes( 0.02f),
One_Centime( 0.01f);
private final float value;
private final String description;
bill(float value) {
this.value = value;
this.description = " " + this.name().replace("_", " ");
}
public float getValue() {
return this.value;
}
@Override
public String toString() {
return this.description;
}
}
my printing function:
public static void getGhange(double price, double cash) {
if (cash < price){
System.out.println("Wrong buddy");
} else if (cash == price) {
System.out.println("Nothing");
} else { //CH > PP
float remaining = (float) (cash - price);
StringBuilder change = new StringBuilder();
for (bill d : bill.values()) {
while (remaining >= d.getValue()) {
remaining -= d.getValue();
change.append(d).append(',');
}
}
change.setLength(change.length() - 1); // remove , at the end
System.out.println(change.toString().trim());
}
}