出力の整形
CoddyのSwiftジャーニー「基礎」セクションの一部 — レッスン 41/86。
チャレンジ
簡単前のレッスンでは、各人が支払う金額を計算しました。今回は、洗練されたプロフェッショナルな出力にするために、通貨の値を小数点以下ちょうど2桁で表示するようにフォーマットします。
Swiftの String(format:) を使用して、tipAmount、totalWithTip、および amountPerPerson の値を小数点以下ちょうど2桁で表示するようにフォーマットしてください。
書式指定子 "%.2f" は、Double 型を小数点以下2桁にフォーマットします:
let formatted = String(format: "%.2f", someDouble)出力を以下の正確な形式で表示するように更新してください:
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]各通貨の値の前に $ 記号が追加され、すべての金額が小数点以下ちょうど2桁で表示されていることに注目してください。
例えば、入力が 85.5、15、3 の場合、出力は以下のようになります:
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自分で試してみよう
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)")
}
}
}