How to format percent in Swift

Issue #639

Never use String(format: "%.2f %%", 1.2 because each region can have different separator and placement of percent sign.

Use NumberFormatter instead

1
2
3
4
5
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.minimumIntegerDigits = 1
formatter.maximumIntegerDigits = 3
formatter.maximumFractionDigits = 2
1
2
3
4
5
formatter.locale = Locale(identifier: "en_US")
formatter.string(from: NSDecimalNumber(decimal: 1.2 / 100)) // 0.12%

formatter.locale = Locale(identifier: "nb_NO")
formatter.string(from: NSDecimalNumber(decimal: 1.2 / 100)) // 0,12 %

Note that the space created by NumberFormatter is a non breakable space \u{00a0}, which can be created by Alt Space. This non breakable space is useful in UILabel when you want the whole word to stick together

Comments