Formatting percent number to zh (simplified Chinese) using the right percent sign (ie. %)

Viewed 198

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).

1 Answers

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.

Related