BLACK FRIDAY: Save 50% on all books and bundles! >>

Formatting interpolated strings in SwiftUI

Paul Hudson    @twostraws   

Updated for Xcode 12.0

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(
    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:

    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:

    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

Save 50% in my Black Friday sale.

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

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

Was this page useful? Let us know!

Average rating: 4.4/5

Link copied to your pasteboard.