我正在为学校写一个收银机计划,我正在添加一个“当前价格”标签。到现在为止还挺好。我试图让价格显示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的“当前价格”时,它将显示没有错误。有小费吗?
您不能使用DecimalFormat
格式化字符串。您可以使用它来格式化double
s:
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])