Formatted Output
Part of the Fundamentals section of Coddy's Swift journey — lesson 41 of 86.
Challenge
EasyIn 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.78Try 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
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input