Showing Decimal value

I am trying to present a decimal variable containing the value of 66.67. So I am trying to do:

Text("\(myVariable, specifier: "%.2f")")
//Instance method 'appendinterpolation(_:specifier) requires that Decimal conform to _formtSpecifiable

Text("\(myVariable, specifier: "%.2f")" as String)
//I receive extra argument specifier in call

How can I fix it ? Thx

Answered by OOPer in 686493022

Unfortunately, the String interpolation of LocalizedStringKey using specifier: requires the value conform to _FormatSpecifiable, to which Decimal does not.

See LocalizedStringKey.StringInterpolation.

String interpolation of String does not support interpolation using specifier:.

See DefaultStringInterpolation.


You can use a String interpolation of LocalizedStringKey using formatter: with value of NSDecimalNumber:

struct ContentView: View {
    let myFormatter: NumberFormatter = {
        let nf = NumberFormatter()
        nf.maximumFractionDigits = 2
        nf.minimumFractionDigits = 2
        return nf
    }()
    
    @State var myVariable: Decimal = Decimal(string: "66.67")!
    
    var body: some View {
        Text("\(myVariable as NSDecimalNumber, formatter: myFormatter)")
    }
}

If Decimal operation is not important for your app, using Double (which conforms to _FormatSpecifiable) might be a good option.

Or you can customize the behavior of String interpolation of LocalizedStringKey, but I'm not sure if it would be a good option.

This should work.

struct ContentView: View {

    @State var testvar:Double = 66.78

    var body: some View {

        Text("\(testvar)")

}

}
Accepted Answer

Unfortunately, the String interpolation of LocalizedStringKey using specifier: requires the value conform to _FormatSpecifiable, to which Decimal does not.

See LocalizedStringKey.StringInterpolation.

String interpolation of String does not support interpolation using specifier:.

See DefaultStringInterpolation.


You can use a String interpolation of LocalizedStringKey using formatter: with value of NSDecimalNumber:

struct ContentView: View {
    let myFormatter: NumberFormatter = {
        let nf = NumberFormatter()
        nf.maximumFractionDigits = 2
        nf.minimumFractionDigits = 2
        return nf
    }()
    
    @State var myVariable: Decimal = Decimal(string: "66.67")!
    
    var body: some View {
        Text("\(myVariable as NSDecimalNumber, formatter: myFormatter)")
    }
}

If Decimal operation is not important for your app, using Double (which conforms to _FormatSpecifiable) might be a good option.

Or you can customize the behavior of String interpolation of LocalizedStringKey, but I'm not sure if it would be a good option.

(The site was malfunctioning, removed.)

Showing Decimal value
 
 
Q