3

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Musection
  • 135
  • 6
  • 1
    Use a single formatter for each unique format, rather than having different number formatters being instantiated all over the place. – Rob May 15 '20 at 17:03
  • 2
    I’m curious: Why would you not want to honor the user’s preference of how numbers should be formatted? – Rob May 15 '20 at 17:03
  • As a training project I am programming a little App that looks like a pocket calculator I used in school. It should show dots no matter what language the user has set up. – Musection May 15 '20 at 18:53

1 Answers1

2

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.

Yann Armelin
  • 691
  • 4
  • 9