Search code examples
c#formattingglobalizationcurrency

C# formatting currency given currency code (like USD / GBP / FRF)


I am integrating with a database which returns currencies (System.Decimal) and currency codes. The currency codes are strings like "USD", "GBP", and even "FRF".

Is there something built-in to mscorlib which can help me format these currencies? I first thought about setting up a mapping between database currency code and CultureInfo, but I don't know what to do about FRF because if I use "fr-FR", it would format as euros instead of francs.

The full list of currency symbols we must support is:

FRF
CHF
NZD
IN2
SAR
SEK
EUR
MXP
DKK
GBP
AUD
IN1
AED
CAD
NOK
INR
USD
PLN

Solution

  • You can replace the default currency and still make use of the framework...

    using System;
    using System.Globalization;
    using System.Threading;
    public class EuroLocalSample
    {
       public static void Main()
       { 
         // Create a CultureInfo object for French in France.
         CultureInfo FrCulture = new CultureInfo("fr-FR");
         // Set the CurrentCulture to fr-FR.
         Thread.CurrentThread.CurrentCulture = FrCulture;
        // Clone the NumberFormatInfo object and create
        // a new object for the local currency of France.
        NumberFormatInfo LocalFormat =
        (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
        // Replace the default currency symbol with the local
        // currency symbol.
        LocalFormat.CurrencySymbol = "F";
    
        int i = 100;
    
        // Display i formatted as the local currency.
        Console.WriteLine(i.ToString("c", LocalFormat));
        // Display i formatted as the default currency.
        Console.WriteLine(i.ToString("c", NumberFormatInfo.CurrentInfo));
       }
    }