Currency formatting in .NET

只谈情不闲聊 提交于 2019-12-05 21:50:28

Absolutely. I've done it using a technique based on a blog post by Matt Weber. Here's an example that uses your culture's format for currency (decimal places, etc.), but uses the currency symbol and number of decimal places appropriate for a given currency code (so one million Yen in the en-US culture would be formatted as ¥1,000,000).

You can, of course, modify it to pick and choose which properties of the current culture and currency's culture are retained.

public static NumberFormatInfo GetCurrencyFormatProviderSymbolDecimals(string currencyCode)
{
    if (String.IsNullOrWhiteSpace(currencyCode))
        return NumberFormatInfo.CurrentInfo;


    var currencyNumberFormat = (from culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                                let region = new RegionInfo(culture.LCID)
                                where String.Equals(region.ISOCurrencySymbol, currencyCode,
                                                    StringComparison.InvariantCultureIgnoreCase)
                                select culture.NumberFormat).First();

    //Need to Clone() a shallow copy here, because GetInstance() returns a read-only NumberFormatInfo
    var desiredNumberFormat = (NumberFormatInfo)NumberFormatInfo.GetInstance(CultureInfo.CurrentCulture).Clone();
    desiredNumberFormat.CurrencyDecimalDigits = currencyNumberFormat.CurrencyDecimalDigits;
    desiredNumberFormat.CurrencySymbol = currencyNumberFormat.CurrencySymbol;

    return desiredNumberFormat;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!