swiftui

Display a Float with specified decimal places in SwiftUI


I am trying to display the value of a Slider in SwiftUI, but I only want one decimal place to show.

I know how to do this in regular Swift by using "%.1f", but that does not work in SwiftUI.


Solution

  • There is nothing special to do about SwiftUI:

    struct ContentView : View {
        let myfloat: Float = 1.2345    
    
        var body: some View {
            let formattedFloat = String(format: "%.1f", myfloat)
            return Text("My Float: \(formattedFloat)")
        }
    }