2017-05-04 54 views
-2

位愚蠢的一個,但我只想澄清我知道我可以輸出格式化爲一個字符串,然後格式化字符串以各種方式來實現這一點,但我需要返回值保持雙倍,因爲它有多種用途。力雙顯示2位小數

所以基本上我有一個LinkedList我在進口時被格式化爲雙讀值。我然後使用這些值的總和基本上計算總我使用的toString功能和一對夫婦的其他地方哪。

我的問題是,如果有尾隨零它們trimed所以值儘可能小。例如:3.50→3.5,0.00→0.0等等。

public double totalCost(){ 
     double total = 0.00; 
     for(Ingredient cost : ingredients){ 
      total += cost.ingredientCost(); 
     } 
     return total; 

上面的代碼是和碼。

public String toString(){ 
     return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + totalCost(); 
    } 

而這是我的toString函數。

任何指導,將是真棒。

+0

所以如果你知道如何格式化雙到字符串,你其實是問?雙只是一個數字,所以沒有這樣的東西作爲「雙存儲3.5」和「雙存儲3.500」是有些不同。 –

回答

0

我認爲這將有助於你:

public String toString(){ 
    return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + String.format("%.2f", totalCost()); 
}