Menu
CoddyTech

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. Formatiere jetzt die Geldbeträge so, dass sie genau 2 Dezimalstellen anzeigen, um eine ansprechende, professionelle Ausgabe zu erhalten.

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

Die Formatangabe "%.2f" formatiert einen Double mit 2 Dezimalstellen:

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

Aktualisiere deine Ausgabe so, dass sie genau dieses Format hat:

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 $ jetzt vor jedem Geldbetrag steht und alle Beträge genau 2 Dezimalstellen anzeigen.

Wenn die Eingaben beispielsweise 85.5, 15 und 3 sind, sollte die Ausgabe so aussehen:

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

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