How can i get currency symbols from currency code in iphone?

前端 未结 9 850
庸人自扰
庸人自扰 2020-12-28 14:55

I have get currency code (Eg: USD, EUR, INR) from webservice response. I need to show the currency symbols for the corresponding currency code. If the currency code is USD,

9条回答
  •  北海茫月
    2020-12-28 15:19

    Swift 4 version

    Finding locale by currency code:

    let localeGBP = Locale
                      .availableIdentifiers
                      .lazy
                      .map { Locale(identifier: $0) }
                      .first { $0.currencyCode == "GBP" }
    print(localeGBP?.currencySymbol) // £
    

    Formatting currency

    if let locale = localeGBP {
      let formatter = NumberFormatter()
      formatter.numberStyle = .currency
      formatter.locale = locale
      let result = formatter.string(from: 100000) // £100,000.00
    }
    

    Edit:

    Why .lazy? Without it the loop would run over all the locale identifiers and return the first one which matches. That's about 700ish identifiers, and if the first one is the one you want then you have wasted creating 699 Locales :) With .lazy in there it automatically stops at the first matching one. In my case it reduces the number of times through the loop from 710 down to 22 when converting "GBP". This isn't important if you are only doing this once, but if you're doing this a number of times (i.e. over an array of symbols) then it's an easy way to get a bit more efficiency.

提交回复
热议问题