Why does NumberFormatter.Style.currency return "XXX"?

Unfortunately, .currency and .currencyISOCode return "XXX" instead of an actual currency symbol or code (see NumberFormatter.Style in the Apple Developer documentation). Do you have an idea, why this occurs? Note that I changed the formatter locale from "en" (which is returned by Locale.current) to "de", but that still returns "XXX".

import SwiftUI
import Foundation

struct ExpenseRow: View {
    
    var body: some View {
        Text(amountAsCurrency())
    }

    fileprivate func amountAsCurrency() -> String {
        let str = "\(format: 35.6689, using: .currency)"
        print(str)
        return str
    }
}

// https://www.hackingwithswift.com/articles/178/super-powered-string-interpolation-in-swift-5-0
extension String.StringInterpolation {
    mutating func appendInterpolation(format value: Float, using style: NumberFormatter.Style) {
        let formatter = NumberFormatter()
        //print("formatter.locale = \(formatter.locale!)")
        //print("Locale.current = \(Locale.current)")
        
        formatter.locale = Locale(identifier: "de")
        formatter.numberStyle = style

        if let result = formatter.string(from: value as NSNumber) {
            appendLiteral(result)
        }
    }
}

Is this really SwiftUI related, or “just” a problem with NumberFormatter?

What happens if you specify the locale as "de_DE", i.e. with language and region?

1 Like

I've edited the following as you suggested and that lets the currency style show the currency symbol. Thanks @Martin
formatter.locale = Locale(identifier: "de_DE")

When I remove that line entirely, thinking that this should return something like $173.04, because formatter.locale defaults to "en", I get this (with actual mock data):

58

:thinking:

Is there an Xcode setting for the locale? The macOS region and language on the iMac I'm on is actually Germany/German.

It seems that this a problem about NumberFormatter (which is part of the Foundation framework) and not a problem about the Swift language. The Apple Developer Forum: Cocoa may be a better place to get help.

I just learned that the GPS position of the Simulator for Xcode is "US" by default and that is why

print("formatter.locale = \(formatter.locale!)")
print("Locale.current = \(Locale.current)")

return "en (current)".

On an actual iOS device, that should be "en_DE (current)"