Menu
Coddy logo textTech

Output formattato

Fa parte della sezione Fondamenti del percorso Swift di Coddy. Lezione 41 di 86.

challenge icon

Sfida

Facile

Nella lezione precedente, hai calcolato quanto paga ogni persona. Ora formatta i valori monetari in modo che mostrino esattamente 2 cifre decimali, per ottenere un risultato curato e professionale.

Usa String(format:) di Swift per formattare i valori tipAmount, totalWithTip e amountPerPerson in modo che mostrino esattamente 2 cifre decimali.

Lo specificatore di formato "%.2f" formatta un Double con 2 cifre decimali:

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

Aggiorna l'output in modo che venga visualizzato esattamente in questo formato:

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]

Nota che il simbolo $ è stato aggiunto prima di ogni valore monetario e che tutti gli importi mostrano esattamente 2 cifre decimali.

Ad esempio, se gli input sono 85.5, 15 e 3, l'output dovrebbe essere:

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

Provalo tu

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)")
        }
    }
}

Tutte le lezioni di Fondamenti

Esercitati da solo: Playground Swift