2

I'd like to use NumberFormatter to generate zh-localised percents as follows, in order to supersede my own code as follow:

    let locale = Locale(identifier: lang)

    let formatter = NumberFormatter()
    formatter.locale = locale
    formatter.numberStyle = .percent
    formatter.maximumFractionDigits = d

    let number = NSNumber(value: Double(n))

    if let r = formatter.string(from: number) {
        if lang == "zh" { return r.replace(["%"], withString: "%")

        return r
    }
    // My fallback code

Unfortunately, unlike my code, in simplified Chinese NumberFormatter generates latin % sign rather than the chinese version (hence the replacement patch I do).

I am wondering if one could tweak NumberFormatter further so that it take care of it? (and in other non-latin languages).

Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95

1 Answers1

3

You seem to imply that what NumberFormatter outputs is incorrect. However, as a native Chinese, I can confidently say that "50%" is the natural way of writing a percentage in the zh locale. This is also evident from this Baidu Baike (Chinese counterpart of Wikipedia) article. I have never seen any app write percentages with the full-width percentage sign. I can't even type it with the Chinese IME on my Mac.

To my eyes, "50%" looks weird, probably because it's mixing full-width and half-width characters. I've occasionally seen "50%" in Japanese sites, but it's still rather rare.

if you really want, you can set the percentSymbol property in NumberFormatter:

let formatter = NumberFormatter()
formatter.percentSymbol = "%"
formatter.numberStyle = .percent
print(formatter.string(from: 0.5) ?? "failed")

To be honest, I would trust the output of NumberFormatter, which is designed by a bunch of professional localisation engineers.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Alas, this does not handle localisation then. – Stéphane de Luca Mar 14 '20 at 20:40
  • @StéphanedeLuca What gave you the idea that Chinese use full-width percent signs? The Japanese seems to use them more in my experience... But anyway, see the edit. – Sweeper Mar 14 '20 at 20:45
  • @StéphanedeLuca In a sense, setting `locale` already _handles_ localisation. `%` _is_ the correct symbol to use in the `zh` locale. What you are saying (that full-width percentage signs should be used in `zh` locale) is your _own_, non-standard kind of localisation that you defined yourself. It is only natural that you have to implement yourself. My suggestion is, just trust what `NumberFormatter` outputs. – Sweeper Mar 14 '20 at 21:02