Display a Float with specified decimal places in SwiftUI

Viewed 6863

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.

3 Answers

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)")
    }
}

Here's how to do it in one line using SwiftUI. “%.2f” is the format code for floating-point number with two digits after the decimal point

Text("You owe me \(balanceDue, specifier: "%.2f") before Tuesday")

iOS 15+

And this option, if you prefer, uses the floating-point format style:

struct ContentView: View {
    let myFloat: Float = 1.2345
    
    var body: some View {
        Text(String(myFloat.formatted(.number.precision(.fractionLength(1)))))
    }
}
Related