Q:

Localizing percentage values

I want to display a string such as:

99 %

According to the Percent sign Wikipedia article, there are at least 13 different variants depending on the user's language.
How can I display a number with the % sign that will appear correct according to the user's locale, in Swift?

A:

You can use NumberFormatter to do so. By default it takes user's current locale into account which you can also get using Locale.current. And if you wish you could change it as well,
func percentFormatted(number: Float, locale: Locale = Locale.current) -> String? {
    let number = (num / 100) as NSNumber
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .percent
    numberFormatter.maximumFractionDigits = 2
    numberFormatter.minimumFractionDigits = 0
    numberFormatter.locale = locale
    return numberFormatter.string(from: number)
}

percentFormatted(number: 99.0) // 99% default locale en_US
percentFormatted(number: 99.0, locale: Locale(identifier: "fi_FI")) // 99 %
percentFormatted(number: 99.0, locale: Locale(identifier: "tr_TR")) // %99

