Reputation: 6578
I want to format a number with an associated currency into a locale-specific string. The standard .ToString("C", CultureInfo.CreateSpecificCulture("xxx"))
produces the wrong output because it uses the locale's currency not the currency that the value actually represents.
I'm looking for a way to do what JQuery Globalize does, but in C# (See here, relavent table below)
Locale ----------------------------------------- 3-letter currency code | en (English) | de (German) | zh (Chinese) ---------------------- | ------------ | ----------- | ------------ USD | $1.00 | 1,00 $ | US$ 1.00 EUR | €1.00 | 1,00 € | € 1.00 CNY | CN¥1.00 | 1,00 CN¥ | ¥ 1.00 JPY | ¥1 | 1 ¥ | JP¥ 1 GBP | £1.00 | 1,00 £ | £ 1.00 BRL | R$1.00 | 1,00 R$ | R$ 1.00
Upvotes: 2
Views: 790
Reputation: 100007
string FormatCurrency(decimal value, string currencyCode, string locale)
{
var culture = CultureInfo.CreateSpecificCulture(locale);
var numberFormat = (NumberFormatInfo) culture.NumberFormat.Clone();
var currencySymbol = CultureInfo.GetCultures(CultureTypes.AllCultures)
.Where(ci => ci!=CultureInfo.InvariantCulture)
.Select(c =>{try{return new RegionInfo(c.LCID);}
catch{return null;}})
.Where(ri=>ri!=null &&
ri.ISOCurrencySymbol==currencyCode)
.Select(ri => ri.CurrencySymbol)
.First();
numberFormat.CurrencySymbol = currencySymbol;
return value.ToString("C",numberFormat);
}
FormatCurrency(1m,"USD","de")
returns "1,00 $"
and so on but it doesn't differentiate between CN¥
and JP¥
, or anything like that, in any locale. The currency symbol is still the one used by its native locale. You can get the extra currency information from the Unicode Common Locale Data Repository (CLDR).
Upvotes: 5