6

How can I generate cardinal numbers(One, Two, Three) using NumberFormatter in Swift using Locale settings.

For example, I am able to convert 1 minute -> One minute using English Locale settings. But for Norwegian it should be Et minutt, While it translates to En minutt which is wrong. Norwegian translation for One is En but when we use it in some sentence, sometimes it should be Et. Here is sample of my code.

let measurement = Measurement(value: 1, unit: UnitDuration.minutes)
let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitStyle = .long
measurementFormatter.locale = Locale(identifier: "nb_no")
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "nb_no")
formatter.numberStyle = .spellOut
measurementFormatter.numberFormatter = formatter
let result = measurementFormatter.string(from: measurement)

Output:

én minutt

Expected Output

et minutt

Umair Aamir
  • 1,624
  • 16
  • 26
  • 3
    Possibly helpful: https://stackoverflow.com/questions/42746121/how-to-handle-special-cases-in-localization-swift. – Martin R Jan 04 '18 at 12:03
  • Yeah this can solve my problem for now but I was looking for some solution using `Formatters` so that my solution can be a generic one. – Umair Aamir Jan 04 '18 at 12:08
  • 1
    Same with the German language: "eins Minute" instead of the correct "Eine Minute". – Interesting problem! – Martin R Jan 04 '18 at 12:10
  • Same with russian language: "один минута" instead of "одна минута", and "два минуты" instead of "две минуты". And ukrainian and belarusian too. Formatting for 1 and 2 is wrong. – user28434'mstep Jan 04 '18 at 12:16
  • My guess would be that the MeasurementFormatter in combination with spellout style does not support correct gender/plural, and the "Plural Rule Properties" in a stringsdict file are your only choice. See e.g. "Plural and Gender Support" in https://www.objc.io/issues/9-strings/string-localization/ – Martin R Jan 04 '18 at 12:18
  • 1
    DateComponentsFormatter has the same problem. – Martin R Jan 04 '18 at 12:32

0 Answers0