Sébastien REMY
Sébastien REMY

Reputation: 2470

SwiftUI : Why format a TextField for currency in EUR set symbol on the left

I try to use a TextField with user locale currency format

I try this

struct MyView: View {
        @State private var amount = 0.0
        
        let currencyFormatter: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.usesGroupingSeparator = true
            formatter.numberStyle = .currency
            formatter.locale = Locale.current
            return formatter
        }()
        
        var body: some View {
            Form {
                // Test 1
                TextField("Amount", value: $amount,
                          formatter: currencyFormatter)
                
                // Test 2
                TextField("Amount", value: $amount,
                          format: .currency(code: Locale.current.currency?.identifier ?? ""))
        }
    }

Both TextField produce the same formatting error :

Amount : €0,00

Expected:

Amount : 0,00 €

For USD it works fine:

Amount : $0.00

Upvotes: 1

Views: 1356

Answers (1)

Sébastien REMY
Sébastien REMY

Reputation: 2470

I just found the solution by adding this to my code:

 Text("Transaction: \(Locale.current.identifier)" )

It render "en_FR"

So in my "project info" I just had "French localization" and know both TextField (Test 1 and Test 2) works fine!

Project

I also had Localizable string file to my project.

Please note a signing difference between Test 1 and Test 2: in Test 1 the user must type the € sign in Test 2 user just have to a value. Make your own test and take the most valuable solution.

Upvotes: 0

Related Questions