Format decimal as currency based on currency code

落爺英雄遲暮 提交于 2019-12-05 04:55:26

You could build a dictionary to go from ISO currency symbol (USD) to currency symbol ($):

static void Main(string[] args)
{
    var symbols = GetCurrencySymbols();

    Console.WriteLine("{0}{1:0.00}", symbols["USD"], 1.5M);
    Console.WriteLine("{0}{1:0.00}", symbols["JPY"], 1.5M);

    Console.ReadLine();
}

static IDictionary<string, string> GetCurrencySymbols()
{
    var result = new Dictionary<string, string>();

    foreach (var ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
    {
        try
        {
            var ri = new RegionInfo(ci.Name);
            result[ri.ISOCurrencySymbol] = ri.CurrencySymbol;                    
        }
        catch { }
    }

    return result;
}

That's the basic idea, you'll need to tweak that to suit your needs.

Note that you can certainly use the CultureInfo class to convert to a string for a specific culture, but as noted in Alexei's comment, that will cause each string to be a little different (like 1.00 vs 1,00). Whichever you use depends on your needs.

jignesh
public static class DecimalExtension
{
    private static readonly Dictionary<string, CultureInfo> ISOCurrenciesToACultureMap =
        CultureInfo.GetCultures(CultureTypes.SpecificCultures)
            .Select(c => new {c, new RegionInfo(c.LCID).ISOCurrencySymbol})
            .GroupBy(x => x.ISOCurrencySymbol)
            .ToDictionary(g => g.Key, g => g.First().c, StringComparer.OrdinalIgnoreCase);

    public static string FormatCurrency(this decimal amount, string currencyCode)
    {
        CultureInfo culture;
        if (ISOCurrenciesToACultureMap.TryGetValue(currencyCode, out culture))
            return string.Format(culture, "{0:C}", amount);
        return amount.ToString("0.00");
    }
}

Here are the results of calling FormatCurrency for a few different currency codes:

decimal amount = 100;

amount.FormatCurrency("AUD");  //$100.00
amount.FormatCurrency("GBP");  //£100.00
amount.FormatCurrency("EUR");  //100,00 €
amount.FormatCurrency("VND");  //100,00 ?
amount.FormatCurrency("IRN");  //? 100.00

Should be done by passing the CultureInfo:

CultureInfo ci = new CultureInfo("en-GB");
amount.ToString("C", ci);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!