Menu
CoddyTech

Output Terformat

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

challenge icon

Tantangan

Mudah

Pada 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:) milik Swift untuk memformat nilai tipAmount, totalWithTip, dan amountPerPerson agar menampilkan tepat 2 angka desimal.

Penentu format "%.2f" memformat Double menjadi 2 angka desimal:

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

Perbarui output agar dicetak dalam format persis berikut:

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, 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 seperti ini:

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

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