【问题标题】:How can I format 2 decimal places in monetary amount?如何格式化货币金额的 2 位小数?
【发布时间】:2020-10-25 05:22:25
【问题描述】:

我被分配了一个问题来设计一个java程序来计算披萨的价格,这是我尝试的:

        String diameter;
        diameter = this.txtInput.getText();
        
        // variable declaration and intialize for "labourCost" and "storeCost"
        double labourCost, storeCost;
        labourCost = 1;
        storeCost = 1.5;       
        
        // convert the value inputted from a string to double
        double dblDiameter= Double.parseDouble(diameter);
        
        // variable declarationa and intialize the value for the variable "cost"
        double cost = (labourCost + storeCost + (0.5 * dblDiameter));
        
        // print the output
        this.lblOutput.setText("The cost of the pizza is $" + cost);

我得到的输出是 7.5 美元,我的问题是如何格式化它以显示 7.50 美元?谢谢。

【问题讨论】:

    标签: java decimal currency decimalformat


    【解决方案1】:

    我正在寻找在 java 中使用货币的不同方法,我遇到了同样的问题。所以看起来 MonetaryAmount 对象不处理格式化,你必须使用格式化对象。

    【讨论】:

    • 这应该是一条评论。
    • @kk.既然你看了这篇文章,你认为它应该是评论,为什么它还在这里?
    【解决方案2】:

    你可以试试DecimalFormat:

    DecimalFormat decimalFormat = new DecimalFormat("#.00");
    

    然后:

    this.lblOutput.setText("The cost of the pizza is $" + decimalFormat.format(cost));
    

    或者你可以使用String.format:

    this.lblOutput.setText("The cost of the pizza is $" + String.format("%.2f", cost));
    

    【讨论】:

    • DecimalFormat("#.##") 在这种情况下不起作用,因为decimalFormat.format(cost) 仍将打印7.5。您需要使用new DecimalFormat("#.00")
    【解决方案3】:

    我推荐你使用BigDecimal#setScale,如下图:

    this.lblOutput.setText("The cost of the pizza is $" + BigDecimal.valueOf(cost).setScale(2, RoundingMode.CEILING));
    

    或者,您可以使用String#format,如下所示:

    this.lblOutput.setText("The cost of the pizza is $" + String.format("%.2f", cost));
    

    另一种选择是使用DecimalFormat#format,如下所示:

    NumberFormat formatter = new DecimalFormat("#.00");
    this.lblOutput.setText("The cost of the pizza is $" + formatter.format(cost));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-26
      • 2015-10-08
      • 2016-04-22
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      相关资源
      最近更新 更多