我在学校的作业中遇到了一些问题,我们必须为一家快餐公司创建一个PoS。部分任务是在输入投标金额后计算更改。我遇到的问题是,程序无法从因“$”而投标的金额中减去总计。我的代码当前如下所示:
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));以及计算变化:
// 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));如何将“$”保存在“grandtotalOutput”框中,但仍然能够正确计算更改?
发布于 2020-12-04 20:33:57
需要从文本中删除$和逗号,以便将它们解析为double数字。您可以通过链接String#replace来做到这一点,首先将,替换为空白文本,然后将$替换为空白文本。
tendered = Double.parseDouble(tenderedInput.getText().replace(",", "").replace("$", ""));
grandtotal = Double.parseDouble(grandtotalOutput.getText().replace(",", "").replace("$", ""));注意:替换可以按任何顺序进行(即先用空白文本替换$,然后用空白文本替换, )。
https://stackoverflow.com/questions/65150228
复制相似问题