簡體   English   中英

顯示數組時如何使用DecimalFormat?

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

我正在為學校編寫收銀機程序,並添加了“當前價格”標簽。 到現在為止還挺好。 我正在嘗試使用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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM