Search code examples
.netlocalizationnumber-formattingglobalizationcurrency-formatting

Format any currency and amount for current culture (not culture of the currency)


I need to format an amount in any given currency so that it looks as expected in the current culture.

For example in UK culture (en-GB) one would expect to see the following:

£1.00 $1.00 €1.00

And in German culture, the same currency amounts should appear as:

1,00 £ 1,00 $ 1,00 €

I have found a method (below) which formats the currency/amount according to the format of the culture associated with the currency (e.g. £1.00, 1,00 €) but this is not quite right, as someone from the UK would expect to see €1.00 even though Euro is not the currency associated with en-GB.

public static string FormatCurrency(this decimal amount, string currencyCode)
{
    var culture = (from c in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                   let r = new RegionInfo(c.LCID)
                   where r != null
                   && r.ISOCurrencySymbol.ToUpper() == currencyCode.ToUpper()
                   select c).FirstOrDefault();

    if (culture == null)
        return amount.ToString("0.00");

    return string.Format(culture, "{0:C}", amount);
}

Can anyone provide or describe a method to view an amount in any given currency according to the current culture?


Solution

  • To set the current symbol to the desired one (£, $, € or whatever else) while still using the other attributes of the current culture, you can just clone your current NumberFormatInfo and replace the currency symbol:

    var cultureInfo = Thread.CurrentThread.CurrentCulture;
    var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
    numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need
    
    var price = 12.3m;
    var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".