I'm making a cash register system with OO and I want to make it modular so you can add different currencies.
So I have this enum to store the currencies:
class Currency {
enum PoundSterlingCurrency {
Fifty_Pounds(50f),
Twenty_Pounds(20f),
Ten_Pounds(10f),
Five_Pounds(5f),
Two_Pounds(2f),
One_Pound(1f),
Fifty_Pence(0.5f),
Twenty_Pence(0.20f),
Ten_Pence(0.10f),
Five_Pence(0.05f),
Two_Pence(0.02f),
One_Pence(0.001f),
private final float value;
private final String description;
PoundSterlingCurrency(float value) {
this.value = value;
this.description = this.name().replace("_", " ");
}
public float getValue() {
return this.value;
}
@Override
public String toString() {
return this.description;
}
}
//Add more currencies here
}
My getChange method
public void getChange(double cash, Product product) {
double cashBack = cash - product.getPrice();
if (currency == Currency.POUNDSTERLING) {
for (PoundSterlingCurrency c : PoundSterlingCurrency.values()) {
while (cashBack >= c.getValue()) {
System.out.println(cashBack);
cashBack -= c.getValue();
}
}
}
}
With the print statement that I have when i calculate the change, I get the following
41.25
21.25
1.25
0.25
0.04999999999999999
0.02999999999999999
In this example, the product has a price of £8.75 and there's £50 that's used to buy it. Therefore, I need to calculate the change.
This shows that when I minus 10 pence away from 25 pence when calculating the change, I somehow get 0.04999...
I could just round the answer each time to check, but surely this isn't good practice if I don't know how this occurs.