tombardey
tombardey

Reputation: 669

Formatting localized numbers with unit symbols

Situation

I want to format a Double 23.54435678 into a String like 23.54 fps respecting the user's locale.

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let formatted = formatter.string(from: fps as NSNumber)! + " fps"

For the localized number formatting I use DateFormatter.

Question

How should I handle the unit part? Is it valid to just append the unit to the formatted number? Is the placement of the symbol not locale dependent? How do I handle that?

Upvotes: 0

Views: 467

Answers (1)

dr_barto
dr_barto

Reputation: 6085

Cocoa has no built-in support for the unit "frames per second", so you will have to provide the suffix yourself, e.g. using Xcode's localization system.

You still need to format the numeric value with NumberFormatter for the current locale and then insert the resulting number string into the localized format string:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let numberString = formatter.string(from: fps)
let formatString = NSLocalizedString("%@ fps", comment: "") // provide localizations via .strings files
let fpsString = String(format: formatString, arguments: numberString)

If unit placement is locale-dependent (you will have to this find out yourself for the target locales of your app), you have to deal with this manually as well. You can leverage the localization system here by providing localizations with an adequately positioned placeholder for the numeric value, e.g. %@ fps for English and x %@ yz for... well, Fantasy Language.

Upvotes: 1

Related Questions