【问题标题】:How to use DecimalFormat when displaying an array?显示数组时如何使用 DecimalFormat?
【发布时间】:2018-10-11 20:33:42
【问题描述】:

我正在为学校编写一个收银机程序,并添加一个“当前价格”标签。到现在为止还挺好。我正在尝试以 2 位小数显示价格,因为如果没有格式,它将以 10 位以上的小数显示价格。这是我的代码:

double aantalProducten [] = {1, 1, 1, 1, 1, 1};

double producten [] = {9.50, 2.95, 1.95, 2.50, 1.00, 1.00};

double totaal [] = {0, 0, 0, 0, 0, 0};

DecimalFormat df = new DecimalFormat("€0.00");

private void BtnPizzaActionPerformed(java.awt.event.ActionEvent 
evt) {                                         
    producten [0] = 9.50;
    aantalProducten[0]++; 
    totaal[0] =+ (producten[0]*aantalProducten[0]);
    LblCurrentPrice.setText(df.format(""+ 
  (totaal[0]+totaal[1]+totaal[2]+totaal[3]+totaal[4]+totaal[5])));

我已经为另外 5 个按钮做到了这一点。但是,当按下按钮时,它会告诉我:“无法将给定的对象格式化为数字”。

我尝试了“Arrays.toString”,但它给出了同样的错误。当显示没有 df.format 的“当前价格”时,它不会显示错误。有什么建议吗?

【问题讨论】:

  • 也许这是一个愚蠢的评论,但如果你初始化你的totaal [] = new double[] {0, 0, 0, 0, 0, 0};有没有关系
  • @Mayhem 我试过“double total [] = new double[] {0, 0, 0, 0, 0, 0};”但它没有用
  • 当你执行这段代码时,程序在哪一行抱怨?你能粘贴整个堆栈跟踪吗?
  • 使用循环来统计值,然后格式化统计本身
  • @F-H 小建议。最好用简单的字母 btnPizzaActionPerformed() 开始方法

标签: java double settext decimalformat


【解决方案1】:

您不能使用DecimalFormat 来格式化字符串。您可以使用它来格式化doubles:

df.format(totaal[0]+totaal[1]+totaal[2]+totaal[3]+totaal[4]+totaal[5])

您通过添加"" + 将总计的值转换为String。同样,没有DecimalFormat.format(String) 方法。

编辑:

也许您想单独显示每个总数,每个总数之间有一个空格,而不是总和,即使您有这样的东西。你可以这样做:

df.format(totaal[0])
+ " " + df.format(totaal[1])
+ " " + df.format(totaal[2])
+ " " + df.format(totaal[3])
+ " " + df.format(totaal[4])
+ " " + df.format(totaal[5])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2011-06-16
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多