Menu
CoddyTech

Output Terformat

Termasuk bagian Dasar-Dasar dalam perjalanan Swift di Coddy. Pelajaran 41 dari 86.

challenge icon

Tantangan

Mudah

Di pelajaran sebelumnya, kamu menghitung jumlah yang dibayar setiap orang. Sekarang, format nilai uang agar ditampilkan dengan tepat 2 angka desimal untuk menghasilkan output yang rapi dan profesional.

Gunakan String(format:) dari Swift untuk memformat nilai tipAmount, totalWithTip, dan amountPerPerson agar menampilkan tepat 2 angka desimal.

Specifier format "%.2f" memformat Double dengan 2 angka desimal:

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

Perbarui output-mu agar tercetak dalam format persis ini:

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]

Perhatikan bahwa simbol $ kini ditambahkan sebelum setiap nilai uang, dan semua jumlah ditampilkan dengan tepat 2 angka desimal.

Misalnya, jika input-nya adalah 85.5, 15, dan 3, output-nya seharusnya:

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

Coba sendiri

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

Semua pelajaran di Dasar-Dasar

Latihan sendiri: Playground Swift