简体   繁体   English

显示数组时如何使用DecimalFormat?

[英]How to use DecimalFormat when displaying an array?

I'm writing a cash register program for school and I'm adding a "current price" label. 我正在为学校编写收银机程序,并添加了“当前价格”标签。 So far so good. 到现在为止还挺好。 I'm trying to make the price display with 2 decimals seeing as without the format it will display prices with 10+ decimals. 我正在尝试使用2位小数显示价格,因为如果没有这种格式,它将显示10位以上的小数价格。 This is my code: 这是我的代码:

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])));

And I've done that for 5 more buttons. 我已经完成了另外5个按钮的操作。 However when pressing a button it will tell me: "Cannot format given Object as a Number". 但是,当按下按钮时,它将告诉我:“无法将给定的对象格式化为数字”。

I tried "Arrays.toString" but it gave the same error. 我尝试了“ Arrays.toString”,但它给出了相同的错误。 When displaying the "current price" without the df.format it will show no error. 当显示不带df.format的“当前价格”时,将不会显示任何错误。 Any tips? 有小费吗?

You can't use DecimalFormat to format a string. 您不能使用DecimalFormat格式化字符串。 You can use it to format double s though: 您可以使用它来格式化double

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

You were casting the value of the sum of totals to String by adding "" + to it. 您通过向其添加"" +将总计的值转换为String Again, there's no DecimalFormat.format(String) method. 同样,没有DecimalFormat.format(String)方法。

Edit: 编辑:

Maybe you wanted to display each total separately with a space between each one, not the sum, even though that's what you had. 也许您想单独显示每个总计,每个间隔之间要有一个空格,而不是总和,即使那是您所拥有的。 This is how you could do that: 这是您可以这样做的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM