Search code examples
iosswiftlocalizationnumberscurrency-formatting

Swift: Formatting currencies with localized million and billion text


I'm working on an app that shows currencies with large numbers. To make it more user friendly it would be nice to show the numbers with letters, e.g:

$24,514,983,671 -> $24.5B // English
3,306,777.10 € -> 3,31 Mio. € // German
kr 23 000 000 -> kr 23 mill. // Norwegian

The numbers should have minimumSignificantDigits = 1 and maximumSignificantDigits = 3.

How should this be solved in Swift? Is there any library available?

Android has this solution

It seems to be based on swift-corelibs-foundation: Github, but I can't see how to use it in my app.

Will I have to make the logic myself with localized translations? I have found an answer for using general abbreviations K/M/B for large numbers here: iOS convert large numbers to smaller format, but it does not solve the whole problem.


Solution

  • You will have to implement your own solution, but it is not hard. One way to go would be to create two dictionaries where the key will be the Locale identifier and the value the translation:

    let millionTrans = [ "en_US" : "million", ...]
    let billionTrans = [ "en_US': "billion", ...]
    

    then get the Locale.current, find out if the amount is in the millions or billions and query the appropriate dictionary to get its value.