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

Formatting interpolated strings in SwiftUI

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

Similar solutions…

BUY OUR BOOKS
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: 5.0/5