2016-03-29 10 views
0

Ich habe einen Code, wo eine Person eine bestimmte Anzahl von Kaffees und Kaffeeportionen in jeder Tasse bestellt, und das Programm berechnet den Gesamtpreis (purchasePrice). Wenn ich den Kaufpreis jedoch als Double ausgabe, gibt es nur eine Zahl mit 1 Dezimalstelle aus. Wie kann ich es ändern, um mit 2 Dezimalstellen auszugeben.Konvertieren von Doppel in 2 Dezimalstellen

double purchasePrice = 0; 
    for (counting = 0; counting < coffeeCups; counting++) { 
    System.out.println("Cup " + (counting + 1) + " has " + coffeeShots[counting] + " shot(s) and will cost $" + (2 + coffeeShots[counting]) + "\n"); 
    purchasePrice+= 2 + (coffeeShots[counting]); 
    } 
    System.out.println(coffeeCups + " coffees to purchase."); 
    System.out.println("\nPurchase price is $" + purchasePrice + "."); 

Antwort

1

Bitte beachten Sie Decimal Format

// 2 places of decimal 
DecimalFormat formatter = new DecimalFormat("#.00"); 

System.out.println(formatter.format(1.23)); // 1.23 
System.out.println(formatter.format(1));  // 1.00 
System.out.println(formatter.format(1.234)); // 1.23 
+0

Immer, wenn ich DecimalFormat in meinem Code Versuchen Sie es mit es kommen mit einem Compiler-Fehler zu sein scheint, dass es nicht das Symbol der ‚DecimalFormat‘ finden kann –

+0

Na, haben Sie um die relevante Klasse zu importieren. Ich glaube, es ist 'java.text.DecimalFormat'. –

+0

@SchahrokhAryana Es wäre nett, wenn Sie eine Antwort annehmen/upvote, wenn Ihr Problem gelöst ist. Von [hier] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), "Die Annahme einer Antwort ist wichtig, da sie sowohl Poster zur Lösung Ihres Problems belohnt als auch andere informiert dass dein Problem gelöst ist. " –

Verwandte Themen