如何在显示数组时使用 DecimalFormat?
How to use DecimalFormat when displaying an array?
我正在为学校编写一个收银机程序,我正在添加一个 "current price" 标签。到目前为止,一切都很好。我正在尝试使价格显示为 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 个按钮。但是,当按下按钮时,它会告诉我:"Cannot format given Object as a Number".
我试过 "Arrays.toString" 但它给出了同样的错误。当显示 "current price" 而没有 df.format 时,它不会显示任何错误。有什么建议吗?
您不能使用 DecimalFormat
来格式化字符串。不过,您可以使用它来格式化 double
s:
df.format(totaal[0]+totaal[1]+totaal[2]+totaal[3]+totaal[4]+totaal[5])
您通过将 "" +
添加到 String
来将总和的值转换为 String
。同样,没有 DecimalFormat.format(String)
方法。
编辑:
也许您想单独显示每个总计,每个总计之间有一个 space,而不是总和,即使那是您所拥有的。您可以这样做:
df.format(totaal[0])
+ " " + df.format(totaal[1])
+ " " + df.format(totaal[2])
+ " " + df.format(totaal[3])
+ " " + df.format(totaal[4])
+ " " + df.format(totaal[5])
我正在为学校编写一个收银机程序,我正在添加一个 "current price" 标签。到目前为止,一切都很好。我正在尝试使价格显示为 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 个按钮。但是,当按下按钮时,它会告诉我:"Cannot format given Object as a Number".
我试过 "Arrays.toString" 但它给出了同样的错误。当显示 "current price" 而没有 df.format 时,它不会显示任何错误。有什么建议吗?
您不能使用 DecimalFormat
来格式化字符串。不过,您可以使用它来格式化 double
s:
df.format(totaal[0]+totaal[1]+totaal[2]+totaal[3]+totaal[4]+totaal[5])
您通过将 "" +
添加到 String
来将总和的值转换为 String
。同样,没有 DecimalFormat.format(String)
方法。
编辑:
也许您想单独显示每个总计,每个总计之间有一个 space,而不是总和,即使那是您所拥有的。您可以这样做:
df.format(totaal[0])
+ " " + df.format(totaal[1])
+ " " + df.format(totaal[2])
+ " " + df.format(totaal[3])
+ " " + df.format(totaal[4])
+ " " + df.format(totaal[5])