Hello,
I am writing a simple Java code, which acts like a Cash Register, However I have faced an issue which I hope to get some help on.
The program:
public class TestItem { private double Order; // instant variable which will be representing the item's price private double Paid; // Paid is an instant variable which represent the amount paid for the item /** * Constructs a Cash Register with zero values */ public TestItem() { Order = 0; Paid = 0; } /** * Initiating the price of the item ordered in the cash register * @param total is the price of the item */ public void recordOrder(double total) { this.Order = Order + total; } /** * Deposit the amount paid by the costumer to the cash registrer * @param dollars is the amount paid */ public void enterPaidValue(double dollars) { Paid = dollars; } /** * Calculate then return the change to the cosutmer */ public double giveChange() { double change = Paid - Order; Order = 0; // after the calculation is done, reset the register value, ready to serve a new costumer Paid = 0; // after the calculation is done, reset the register value, ready to serve a new costumer[/COLOR] return change; // return the change } }
Well yes it is easy as it looks, now after coding the tester program:
/** * This class is a tester class */ public class TestItemTester { /** * Main method. */ public static void main(String[] args) { TestItem register = new TestItem(); // creating a new object of the class TestItem register.recordOrder(19.93); // calling the method recordOrder and initiating parameters, this is // the cost of the Item. register.enterPaidValue(20); // calling the method enterPaidValue, initiating parameter, this is // the amount that the costumer have paid.[/COL System.out.print("Change: "); System.out.println(register.giveChange()); // calling giveChange method to pring out the change. } }
Everything is going smooth, except of the result of giveChange() method, after calling giveChange() method the result turns out to be: "Change: 0.07000000000000028", I know this is happening becuase of the behaviour of the primitive type "double", which is basicly occuring the (rounding error).
I am trying to result a better output, like "0.07" instead of "0.07000000000000028" as this will confuse the cashier, any thoughts?
Regards,