55

在 C# 中,是否可以从 3 个字符的货币代码(在本例中为“GBP”)中获取货币符号,例如“£”?

这在 SQL Server 或 C# 中是否可行?

4

9 回答 9

94

虽然有点蛮力而且不是特别优雅,但您可以这样做:

public bool TryGetCurrencySymbol(string ISOCurrencySymbol, out string symbol)
{
    symbol = CultureInfo
        .GetCultures(CultureTypes.AllCultures)
        .Where(c => !c.IsNeutralCulture)
        .Select(culture => {
            try{
                return new RegionInfo(culture.Name);
            }
            catch
            {
                return null;
            }
        })
        .Where(ri => ri!=null && ri.ISOCurrencySymbol == ISOCurrencySymbol)
        .Select(ri => ri.CurrencySymbol)
        .FirstOrDefault();
    return symbol != null;
}

并按如下方式使用它:

string currSymbol;
if(TryGetCurrencySymbol("GBP",out currSymbol))
{
    Console.WriteLine("symbol is {0}", currSymbol);
}

如果您预计会采用这种方法,那么最好预先构建一个缓存:

public static class CurrencyTools
{
    private static IDictionary<string,string> map;
    static CurrencyTools()
    {
        map = CultureInfo
            .GetCultures(CultureTypes.AllCultures)
            .Where(c => !c.IsNeutralCulture)
            .Select(culture => {
                try{
                    return new RegionInfo(culture.Name);
                }
                catch
                {
                    return null;
                }
            })
            .Where(ri => ri!=null)
            .GroupBy(ri => ri.ISOCurrencySymbol)
            .ToDictionary(x => x.Key, x => x.First().CurrencySymbol);
    }
    public static bool TryGetCurrencySymbol(
                          string ISOCurrencySymbol, 
                          out string symbol)
    {
        return map.TryGetValue(ISOCurrencySymbol,out symbol);
    }
}

在撰写本文时,在我的机器等上,地图包含以下映射:

AED  د.إ.‏
AFN  ؋
ALL  Lekë
AMD  ֏
ANG  NAf.
AOA  Kz
ARS  $
AUD  $
AWG  Afl.
AZN  ₼
BAM  КМ
BBD  $
BDT  ৳
BGN  лв.
BHD  د.ب.‏
BIF  FBu
BMD  $
BND  $
BOB  Bs
BRL  R$
BSD  $
BTN  Nu.
BWP  P
BYN  Br
BZD  $
CAD  $
CDF  FC
CHF  CHF
CLP  $
CNY  ¥
COP  $
CRC  ₡
CUP  $
CVE  ​
CZK  Kč
DJF  Fdj
DKK  kr.
DOP  $
DZD  د.ج.‏
EGP  ج.م.‏
ERN  Nfk
ETB  Br
EUR  €
FJD  $
FKP  £
GBP  £
GEL  ₾
GHS  GH₵
GIP  £
GMD  D
GNF  FG
GTQ  Q
GYD  $
HKD  $
HNL  L
HRK  kn
HTG  G
HUF  Ft
IDR  Rp
ILS  ₪
INR  ₹
IQD  د.ع.‏
IRR  ريال
ISK  kr
JMD  $
JOD  د.ا.‏
JPY  ¥
KES  Ksh
KGS  сом
KHR  ៛
KMF  CF
KPW  ₩
KRW  ₩
KWD  د.ك.‏
KYD  $
KZT  ₸
LAK  ₭
LBP  ل.ل.‏
LKR  රු.
LRD  $
LYD  د.ل.‏
MAD  د.م.‏
MDL  L
MGA  Ar
MKD  ден
MMK  K
MNT  ₮
MOP  MOP$
MRU  MRU
MUR  Rs
MVR  ރ.
MWK  MK
MXN  $
MYR  RM
MZN  MTn
NAD  $
NGN  ₦
NIO  C$
NOK  kr
NPR  रु
NZD  $
OMR  ر.ع.‏
PAB  B/.
PEN  S/
PGK  K
PHP  ₱
PKR  Rs
PLN  zł
PYG  ₲
QAR  ر.ق.‏
RON  lei
RSD  дин.
RUB  ₽
RWF  RF
SAR  ر.س.‏
SBD  $
SCR  SR
SDG  ج.س.
SEK  kr
SGD  $
SHP  £
SLL  Le
SOS  S
SRD  $
SSP  £
STN  Db
SYP  ل.س.‏
SZL  E
THB  ฿
TJS  смн
TMT  m.
TND  د.ت.‏
TOP  T$
TRY  ₺
TTD  $
TWD  NT$
TZS  TSh
UAH  ₴
UGX  USh
USD  $
UYU  $
UZS  сўм
VES  Bs.S
VND  ₫
VUV  VT
WST  WS$
XAF  FCFA
XCD  EC$
XDR  XDR
XOF  CFA
XPF  FCFP
YER  ر.ي.‏
ZAR  R
ZMW  K
于 2012-09-11T16:50:02.810 回答
46

.NET 有CultureInfo.NumberFormat.CurrencySymbol

CultureInfo us = new CultureInfo("en-US");
CultureInfo gb = new CultureInfo("en-GB");
CultureInfo fr = new CultureInfo("fr-FR");

Console.Out.WriteLine(us.NumberFormat.CurrencySymbol); // $
Console.Out.WriteLine(gb.NumberFormat.CurrencySymbol); // £
Console.Out.WriteLine(fr.NumberFormat.CurrencySymbol); // €

但这需要文化名称,而不是"GBP". 据我所知,它不可能直接来自"GBP"等。

相同的信息也可通过RegionInfo以及货币代码获得:

RegionInfo us = new RegionInfo("en-US");
RegionInfo gb = new RegionInfo("en-GB");
RegionInfo fr = new RegionInfo("fr-FR");

Console.Out.WriteLine(us.CurrencySymbol); // $
Console.Out.WriteLine(gb.CurrencySymbol); // £
Console.Out.WriteLine(fr.CurrencySymbol); // €

Console.Out.WriteLine(us.ISOCurrencySymbol); // USD
Console.Out.WriteLine(gb.ISOCurrencySymbol); // GBP
Console.Out.WriteLine(fr.ISOCurrencySymbol); // EUR

我想人们可以想象使用它来构建从 ISO 代码到符号的映射。

文化名称列表可在此处获得。

编辑:这似乎有效:

public static class CurrencyCodeMapper
{
    private static readonly Dictionary<string, string> SymbolsByCode;

    public static string GetSymbol(string code) { return SymbolsByCode[code]; }

    static CurrencyCodeMapper()
    {
        SymbolsByCode = new Dictionary<string, string>();

        var regions = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                      .Select(x => new RegionInfo(x.LCID));

        foreach (var region in regions)
            if (!SymbolsByCode.ContainsKey(region.ISOCurrencySymbol))
                SymbolsByCode.Add(region.ISOCurrencySymbol, region.CurrencySymbol);
    }
}

用法:

CurrencyCodeMapper.GetSymbol("USD") // $
CurrencyCodeMapper.GetSymbol("GBP") // £
CurrencyCodeMapper.GetSymbol("EUR") // €

当然,请注意,这不会产生一个完整的列表。特别是,它不包括已被欧元取代的旧欧元区货币。我看不到任何解决方法,只能在需要时手动添加此类货币,例如SymbolsByCode.Add("FRF", "₣");法郎。

于 2012-09-11T16:12:55.987 回答
8

RegionInfo 类有一个CurrencySymbol 属性,所以它在 C# 中是可行的。如果您想在 Sql Server 中执行此操作,您也许可以使用 C# 存储过程。

RegionInfo regionInfo = new RegionInfo("GB");
Console.WriteLine(regionInfo.CurrencySymbol); // £

(您需要使用ISO 国家代码

于 2012-09-11T16:11:17.207 回答
6

这不适用于 Windows Phone 应用程序,因为CultureInfo.GetCultures该平台上不可用(至少目前还没有)。因此,这是一个快速而肮脏的解决方案-在花费者的答案的帮助下完成,该答案包含当时的所有文化代码和货币。

public static class CurrencyHelper
{
    public static string GetCurrencySymbol(string code)
    {
        if (Currencies.ContainsKey(code))
        {
            return Currencies[code];
        }
        else
        {
            return code;
        }
    }

    public static Dictionary<string, string> Currencies = new Dictionary<string, string>() {
                                                    {"AED", "د.إ.‏"},
                                                    {"AFN", "؋ "},
                                                    {"ALL", "Lek"},
                                                    {"AMD", "դր."},
                                                    {"ARS", "$"},
                                                    {"AUD", "$"}, 
                                                    {"AZN", "man."}, 
                                                    {"BAM", "KM"}, 
                                                    {"BDT", "৳"}, 
                                                    {"BGN", "лв."}, 
                                                    {"BHD", "د.ب.‏ "},
                                                    {"BND", "$"}, 
                                                    {"BOB", "$b"}, 
                                                    {"BRL", "R$"}, 
                                                    {"BYR", "р."}, 
                                                    {"BZD", "BZ$"}, 
                                                    {"CAD", "$"}, 
                                                    {"CHF", "fr."}, 
                                                    {"CLP", "$"}, 
                                                    {"CNY", "¥"}, 
                                                    {"COP", "$"}, 
                                                    {"CRC", "₡"}, 
                                                    {"CSD", "Din."}, 
                                                    {"CZK", "Kč"}, 
                                                    {"DKK", "kr."}, 
                                                    {"DOP", "RD$"}, 
                                                    {"DZD", "DZD"}, 
                                                    {"EEK", "kr"}, 
                                                    {"EGP", "ج.م.‏ "},
                                                    {"ETB", "ETB"}, 
                                                    {"EUR", "€"}, 
                                                    {"GBP", "£"}, 
                                                    {"GEL", "Lari"}, 
                                                    {"GTQ", "Q"}, 
                                                    {"HKD", "HK$"}, 
                                                    {"HNL", "L."}, 
                                                    {"HRK", "kn"}, 
                                                    {"HUF", "Ft"}, 
                                                    {"IDR", "Rp"}, 
                                                    {"ILS", "₪"}, 
                                                    {"INR", "रु"}, 
                                                    {"IQD", "د.ع.‏ "},
                                                    {"IRR", "ريال "},
                                                    {"ISK", "kr."}, 
                                                    {"JMD", "J$"}, 
                                                    {"JOD", "د.ا.‏ "},
                                                    {"JPY", "¥"}, 
                                                    {"KES", "S"}, 
                                                    {"KGS", "сом"}, 
                                                    {"KHR", "៛"}, 
                                                    {"KRW", "₩"}, 
                                                    {"KWD", "د.ك.‏ "},
                                                    {"KZT", "Т"}, 
                                                    {"LAK", "₭"}, 
                                                    {"LBP", "ل.ل.‏ "},
                                                    {"LKR", "රු."}, 
                                                    {"LTL", "Lt"}, 
                                                    {"LVL", "Ls"}, 
                                                    {"LYD", "د.ل.‏ "},
                                                    {"MAD", "د.م.‏ "},
                                                    {"MKD", "ден."}, 
                                                    {"MNT", "₮"}, 
                                                    {"MOP", "MOP"}, 
                                                    {"MVR", "ރ."}, 
                                                    {"MXN", "$"}, 
                                                    {"MYR", "RM"}, 
                                                    {"NIO", "N"}, 
                                                    {"NOK", "kr"}, 
                                                    {"NPR", "रु"}, 
                                                    {"NZD", "$"}, 
                                                    {"OMR", "ر.ع.‏ "},
                                                    {"PAB", "B/."}, 
                                                    {"PEN", "S/."}, 
                                                    {"PHP", "PhP"}, 
                                                    {"PKR", "Rs"}, 
                                                    {"PLN", "zł"}, 
                                                    {"PYG", "Gs"}, 
                                                    {"QAR", "ر.ق.‏ "},
                                                    {"RON", "lei"}, 
                                                    {"RSD", "Din."}, 
                                                    {"RUB", "р."}, 
                                                    {"RWF", "RWF"}, 
                                                    {"SAR", "ر.س.‏ "},
                                                    {"SEK", "kr"}, 
                                                    {"SGD", "$"}, 
                                                    {"SYP", "ل.س.‏ "},
                                                    {"THB", "฿"}, 
                                                    {"TJS", "т.р."}, 
                                                    {"TMT", "m."}, 
                                                    {"TND", "د.ت.‏ "},
                                                    {"TRY", "TL"}, 
                                                    {"TTD", "TT$"}, 
                                                    {"TWD", "NT$"}, 
                                                    {"UAH", "₴"}, 
                                                    {"USD", "$"}, 
                                                    {"UYU", "$U"}, 
                                                    {"UZS", "so'm"}, 
                                                    {"VEF", "Bs. F."}, 
                                                    {"VND", "₫"}, 
                                                    {"XOF", "XOF"}, 
                                                    {"YER", "ر.ي.‏ "},
                                                    {"ZAR", "R"}, 
                                                    {"ZWL", "Z$"} };
}
于 2014-08-31T16:54:41.667 回答
4

试试这个代码。输入“USD”作为 CurrencyCode 和所有其他。

public string getCurrencySymbol(string CurrencyCode)    
{
        string symbol = string.Empty;
        CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
        IList Result = new ArrayList();
        foreach (CultureInfo ci in cultures)
        {
            RegionInfo ri = new RegionInfo(ci.LCID);
            if (ri.ISOCurrencySymbol == CurrencyCode)
            {
                symbol = ri.CurrencySymbol;
                return symbol;
            }
        }
        return symbol;

    }
于 2013-02-15T11:22:30.930 回答
1

在这个线程的帮助下,我做了一个短字符串扩展方法

public static string ToCurrencySymbol(this string ISOCurrency)
{            
    RegionInfo region = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(x => new RegionInfo(x.LCID)).FirstOrDefault(p => p.ISOCurrencySymbol == ISOCurrency);
    return region?.ISOCurrencySymbol ?? ISOCurrency;
}
于 2017-10-08T13:42:02.737 回答
0

这个答案将@spender 的代码稍作调整放在一个实用程序类中,该类尝试将三字母 ISO 货币代码转换为其当前流通的符号。为了提高效率,此类使用所有先前请求的内部缓存,@spender 也建议。

public static class CurrencySymbolMapper {
    /// <summary>An internal cache of previously looked up currencies.</summary>
    private static Dictionary<string, string> _currencySymbolsCache =
        new Dictionary<string, string> (StringComparer.CurrentCultureIgnoreCase);

    public static string TryGetCurrencySymbol(string threeLetterISOAlphabeticCode) {
        // TODO: Enhance to get rid of the silent exception that gets thrown when constructing a new RegionInfo(CultureInfo.LCID) temporary object

        if (threeLetterISOAlphabeticCode.Length != 3) return string.Empty;
        if (_currencySymbolsCache.ContainsKey(threeLetterISOAlphabeticCode))
            return _currencySymbolsCache[threeLetterISOAlphabeticCode];

        string currencySymbolSearchResult = string.Empty;
        try {
            currencySymbolSearchResult =
                CultureInfo.GetCultures(CultureTypes.AllCultures)
                            .Where(c => !c.IsNeutralCulture)
                            .Select(culture => {
                                try { return new RegionInfo(culture.LCID); }
                                catch { return null; } // Ignore this error, but enhance future implementation to get ride of this silent exception
                            })
                            .Where(ri => ri != null && string.Equals(ri.ISOCurrencySymbol, threeLetterISOAlphabeticCode, StringComparison.OrdinalIgnoreCase))
                            .Select(ri => ri.CurrencySymbol)
                            .FirstOrDefault();
        }
        catch (Exception e) {
            // TODO: Handle error
        }

        if (currencySymbolSearchResult == null) currencySymbolSearchResult = string.Empty;

        // Saves both valid and invalid search results, just in case users hammer this method with 
        // the same invalid request many times
        _currencySymbolsCache.Add(threeLetterISOAlphabeticCode, currencySymbolSearchResult);
        return currencySymbolSearchResult;
    }
}
于 2017-04-17T17:52:37.293 回答
0
public static string GetCurrencySymbol(string code)  
{  
 System.Globalization.RegionInfo regionInfo = (from culture in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.InstalledWin32Cultures)  
              where culture.Name.Length > 0 && !culture.IsNeutralCulture  
              let region = new System.Globalization.RegionInfo(culture.LCID)  
              where String.Equals(region.ISOCurrencySymbol, code, StringComparison.InvariantCultureIgnoreCase)  
              select region).First();  

 return regionInfo.CurrencySymbol;  
}
于 2017-06-07T17:02:04.973 回答
0

这就是我获得 DECLARE @CultureCode varchar(10) = 'en-us' 的方式

SELECT SUBSTRING(FORMAT(CONVERT(money,0), 'C', @CultureCode ),1,1) CurrencySymbol

于 2019-12-05T11:37:37.987 回答