Menu
Coddy logo textTech

Formatierte Ausgabe

Teil des Abschnitts Grundlagen der Swift-Journey von Coddy. Lektion 41 von 86.

challenge icon

Aufgabe

Einfach

In der vorherigen Lektion hast du berechnet, wie viel jede Person bezahlt. Jetzt formatierst du die Geldwerte so, dass sie genau 2 Dezimalstellen anzeigen, um eine saubere, professionelle Ausgabe zu erhalten.

Verwende Swifts String(format:), um die Werte tipAmount, totalWithTip und amountPerPerson so zu formatieren, dass sie genau 2 Dezimalstellen anzeigen.

Der Formatbezeichner "%.2f" formatiert ein Double auf 2 Dezimalstellen:

let formatted = String(format: "%.2f", someDouble)

Aktualisiere deine Ausgabe, um sie in genau diesem Format auszugeben:

Welcome to the Bill Split Calculator!
Bill: [billTotal]
Tip: [tipPercentage]%
People: [numberOfPeople]
Tip amount: $[tipAmount formatted]
Total with tip: $[totalWithTip formatted]
Each person pays: $[amountPerPerson formatted]

Beachte, dass das $-Symbol nun vor jedem Geldwert hinzugefügt wurde und alle Beträge genau 2 Dezimalstellen anzeigen.

Wenn die Eingaben zum Beispiel 85.5, 15 und 3 sind, sollte die Ausgabe wie folgt aussehen:

Welcome to the Bill Split Calculator!
Bill: 85.5
Tip: 15%
People: 3
Tip amount: $12.83
Total with tip: $98.33
Each person pays: $32.78

Probier es selbst

print("Welcome to the Bill Split Calculator!")

if let billInput = readLine(), let billTotal = Double(billInput) {
    if let tipInput = readLine(), let tipPercentage = Int(tipInput) {
        if let peopleInput = readLine(), let numberOfPeople = Int(peopleInput) {
            let tipAmount = billTotal * Double(tipPercentage) / 100
            let totalWithTip = billTotal + tipAmount
            let amountPerPerson = totalWithTip / Double(numberOfPeople)
            
            print("Bill: \(billTotal)")
            print("Tip: \(tipPercentage)%")
            print("People: \(numberOfPeople)")
            print("Tip amount: \(tipAmount)")
            print("Total with tip: \(totalWithTip)")
            print("Each person pays: \(amountPerPerson)")
        }
    }
}

Alle Lektionen in Grundlagen

Übe selbstständig: Swift-Playground