快速从货币代码中获取货币符号 [英] Get currency symbols from currency code with swift

查看:581
本文介绍了快速从货币代码中获取货币符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Swift(macOS)获得相应货币代码的货币符号.

How can I get the currency symbols for the corresponding currency code with Swift (macOS).

示例:

  • EUR =€1.00
  • 美元= $ 1.00
  • CAD = 1.00美元
  • 英镑= 1.00英镑

我的代码:

var formatter = NSNumberFormatter()
formatter.currencySymbol = getSymbol(currencyCode)
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
let number = NSNumber(double: (amount as NSString).doubleValue)
let amountWithSymbol = formatter.stringFromNumber(number)!

getSymbol(_ currencyCode: String) -> String

还是..有更好的方法吗?

or.. is there a better way?

推荐答案

有点晚了,但这是我用来获取货币符号的美元而不是美元等的解决方案.

A bit late but this is a solution I used to get the $ instead of US$ etc. for currency symbol.

/*
 * Bear in mind not every currency have a corresponding symbol. 
 *
 * EXAMPLE TABLE
 *
 * currency code | Country & Currency | Currency Symbol
 *
 *      BGN      |   Bulgarian lev    |      лв   
 *      HRK      |   Croatian Kuna    |      kn
 *      CZK      |   Czech  Koruna    |      Kč
 *      EUR      |       EU Euro      |      €
 *      USD      |     US Dollar      |      $
 *      GBP      |   British Pound    |      £
 */

func getSymbol(forCurrencyCode code: String) -> String? {
   let locale = NSLocale(localeIdentifier: code)
   return locale.displayNameForKey(NSLocaleCurrencySymbol, value: code)
}

基本上,这将从您的货币代码创建NSLocale,并获取该货币的显示属性.如果结果与货币代码匹配,例如SEK,它将通过删除货币代码中的最后一个字符并将"_en"附加到SE_en中来创建新的国家/地区特定语言环境.然后它将尝试再次获取货币符号.

Basically this creates NSLocale from your currency code and grabs the display attribute for the currency. In cases where the result matches the currency code for example SEK it will create new country specific locale by removing the last character from the currency code and appending "_en" to form SE_en. Then it will try to get the currency symbol again.

Swift 3& 4

func getSymbol(forCurrencyCode code: String) -> String? {
    let locale = NSLocale(localeIdentifier: code)
    if locale.displayName(forKey: .currencySymbol, value: code) == code {
        let newlocale = NSLocale(localeIdentifier: code.dropLast() + "_en")
        return newlocale.displayName(forKey: .currencySymbol, value: code)
    }
    return locale.displayName(forKey: .currencySymbol, value: code)
}

这篇关于快速从货币代码中获取货币符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆