NEW: Join my free 100 Days of SwiftUI challenge today! >>

Formatting interpolated strings in SwiftUI

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

OK, let’s fix up that order total so that it’s accurate. We’re going to add a totalPrice computed property to our type, which will calculate the value of their tip, add it to the total for their order, and return that amount.

Please add this to CheckoutView now:

var totalPrice: Double {
    let total = Double(order.total)
    let tipValue = total / 100 * Double(Self.tipAmounts[tipAmount])
    return total + tipValue
}

Now, remember that SwiftUI will re-invoke our body property whenever any of our @State properties change. As a result, we can use that computed property right inside our layout, and it will automatically change as the segmented control changes:

Section(header:
    Text("TOTAL: $\(totalPrice)")
) {

If you try that out you should see it all work more or less correctly, but take a look at the way our total price is formatted – $23.000000 isn’t the kind of thing users would expect to see when buying some food.

This happens because we’ve placed a Double into a string, so Swift shows us the full value of that number. What we want to happen is to format the number so that two decimal places are visible, and helpfully SwiftUI comes with a specialized string interpolation that lets us do just that. Replace the above code with this:

Section(header:
    Text("TOTAL: $\(totalPrice, specifier: "%.2f")")
) { 

“%.2f” is the format code for “floating-point number with two digits after the decimal point”, and should make our UI look much better. If you’d like a challenge, why not try changing totalPrice to use a NumberFormatter?

Further reading

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!