Can I use a different number format across my app without changing the whole Locale?

Viewed 137

I would like to keep the user’s language setting but force english style number formatting.

So, say the user has their iPad set up in Hungarian. All the words should get drawn from the Hungarian Localizable.strings file.

BUT! I want to show all numbers formatted with a dot as decimal separator (so 1½ should be 1.5 instead of 1,5 what is the default for Hungary, they use a comma as the decimal separator).

How can I achieve that, without setting every NumberFormatter in my app to that locale?

Is there a separate app wide setting for language and region?

1 Answers

You can create a subclass of NumberFormatter that will be automatically initialized with an English locale.

class EnglishNumberFormatter: NumberFormatter {
    private static let EnglishLocale = Locale(identifier: "en")
    override init() {
        super.init()
        self.locale = EnglishFormatter.EnglishLocale
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.locale = EnglishFormatter.EnglishLocale
    }
}

Then simply use EnglishNumberFormatter instead NumberFormatter when you need it.

Related