I am running into issues with my school assignment, where we have to create a PoS for a fast food company. Part of the assignment is calculating change after typing in the amount tendered. The problem I am having is the program cannot subtract the grand total from the amount tendered due to '$'. My code currently looks like this:
private void totalButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Finding the subtotal
double burgers;
double fries;
double drinks;
double subtotal;
burgers = 2.49;
fries = 1.89;
drinks = 0.99;
subtotal = Double.parseDouble (burgerInput.getText ()) * burgers
+ Double.parseDouble (fryInput.getText ()) * fries
+ Double.parseDouble (drinkInput.getText ()) * drinks;
DecimalFormat w = new DecimalFormat("###,###0.00");
subtotalOutput.setText("$" + w.format(subtotal));
// Calculating Tax
double taxpercentage;
double tax;
taxpercentage = 0.13;
tax = subtotal * taxpercentage;
DecimalFormat x = new DecimalFormat("###,###0.00");
taxesOutput.setText("$" + x.format(tax));
// Grand Total
double grandtotal;
grandtotal = subtotal + tax;
DecimalFormat y = new DecimalFormat("###,###0.00");
grandtotalOutput.setText("$" + y.format(grandtotal));
and for calculating change:
// Calculating Change
double tendered;
double grandtotal;
double change;
tendered = Double.parseDouble(tenderedInput.getText ());
grandtotal = Double.parseDouble(grandtotalOutput.getText ());
change = tendered - grandtotal;
DecimalFormat z = new DecimalFormat("###,###0.00");
changeOutput.setText("$" + z.format(change));
How can I keep the '$' in the grandtotalOutput
box but still be able to calculate the change properly?
The $
and comma need to be removed from the text in order for it to be parsed into a double
number. You can do so by chaining String#replace
, first to replace ,
with a blank text and then $
with a blank text.
tendered = Double.parseDouble(tenderedInput.getText().replace(",", "").replace("$", ""));
grandtotal = Double.parseDouble(grandtotalOutput.getText().replace(",", "").replace("$", ""));
Note: The replacements can be done in any order (i.e. first replace $
with a blank text and then ,
with a blank text).