iosswiftswiftuinsnumberformatterswiftui-text

How to use a NumberFormatter in SwiftUI?


I'm trying to use the below NumberFormatter but can't figure out how to use it in a Text view? Everything online relates to a TextView.

 static let numberFormat: NumberFormatter =  {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .none
        numberFormatter.positivePrefix = "+"
        numberFormatter.negativePrefix = "-"
        return numberFormatter
    }()

My attempted usage: but I am getting the error Instance method 'appendInterpolation(_:formatter:)' requires that 'Int' inherit from 'NSObject'

Text("\(450, formatter: Self.numberFormat)")

Solution

  • Here is a simple way:

    With this way, you would keep your @State as clean as possible. Also, the formatterFunction(number: Int) is reusable now and accessible from everywhere in comparison to your way, which would not be reusable or accessible.


    extension Formatter {
        static let number: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.numberStyle = .none
            formatter.positivePrefix = "+"
            formatter.negativePrefix = "-"
            return formatter
        }()
    }
    

    func formatterFunction(number: Int) -> String {
        Formatter.number.string(for: number) ?? ""
    }
    

    struct ContentView: View {
        @State var number: Int = 450
        var body: some View { 
            Text(formatterFunction(number: number))
        }
    }
    

    If you just want to add + and - to your Text, then use simply this function below:

    func formatterFunction(number: Int) -> String {
        if number > 0 {
            return "+" + String(number)
        }
        else if number < 0 {
            return "-" + String(abs(number))
        }
        else {
            return String(number)
        }
    }