Search code examples
doubleswiftuistring-interpolation

SwiftUI - Display Double rounded to 2 decimal places


I have a dollar ( monetary) amount that I'm trying to display using string interpolation in a Text element. Currently, it displays such as 9.9900000. I want the value just to display as 9.99.

struct ContentView: View {
var productPrice: Double = 9.99

    var body: some View {
       Text("\(productPrice)")
    }
}

Solution

  • struct ContentView: View {
    var productPrice: Double = 9.99
        var body: some View {
           Text("\(productPrice, specifier: "%.2f")")
        }
    }