Menu
Coddy logo textTech

Formatted Output

Part of the Fundamentals section of Coddy's Swift journey. Lesson 41 of 86.

challenge icon

Challenge

Easy

In the previous lesson, you calculated how much each person pays. Now, format the monetary values to display exactly 2 decimal places for a polished, professional output.

Use Swift's String(format:) to format the tipAmount, totalWithTip, and amountPerPerson values to show exactly 2 decimal places.

The format specifier "%.2f" formats a Double to 2 decimal places:

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

Update your output to print in this exact format:

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]

Notice the $ symbol is now added before each monetary value, and all amounts show exactly 2 decimal places.

For example, if the inputs are 85.5, 15, and 3, the output should be:

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

Try it yourself

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

All lessons in Fundamentals

Practice on your own: Swift playground