java-忽略gettext中的“$”

bttbmeg0  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(366)

我的学校作业遇到了问题,我们必须为一家快餐公司创建一个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框中保留“$”,但仍然能够正确计算更改,我将不胜感激。谢谢!

mqkwyuun

mqkwyuun1#

这个 $ 需要从文本中删除逗号才能将其解析为 double 号码。你可以用链子锁起来 String#replace ,首先替换 , 空白文本,然后 $ 空白文本。

tendered = Double.parseDouble(tenderedInput.getText().replace(",", "").replace("$", ""));
grandtotal = Double.parseDouble(grandtotalOutput.getText().replace(",", "").replace("$", ""));

注:更换可按任何顺序进行(即首次更换 $ 空白文本,然后 , 空白文本)。

相关问题