Currency format for display

前端 未结 7 1190
忘了有多久
忘了有多久 2020-11-27 06:50

Is there a way to format the correct currency representation for a country?

Example UK -£127.54 Netherlands € 127,54- USA $127.54

etc..

Some things to

7条回答
  •  时光取名叫无心
    2020-11-27 07:23

    The problem with taking a given number and displaying it with .ToString("C", culture) is that it effectively changes the amount to the default currency of the given culture. If you have a given amount, the ISO currency code of that amount, and you want to display it for a given culture, I would recommend just creating a decimal extension method like the one below. This will not automatically assume that the currency is in the default currency of the culture:

    public static string ToFormattedCurrencyString(
        this decimal currencyAmount,
        string isoCurrencyCode,
    CultureInfo userCulture)
    {
        var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;
    
        if (userCurrencyCode == isoCurrencyCode)
        {
            return currencyAmount.ToString("C", userCulture);
        }
    
        return string.Format(
            "{0} {1}", 
            isoCurrencyCode, 
            currencyAmount.ToString("N2", userCulture));
    }
    

    This will either use the local currency symbol or the ISO currency code with the amount -- whichever is more appropriate. More on the topic in this blog post.

提交回复
热议问题