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
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.
I would take this approach, but make a custom IFormatProvider
for FRF that does the formatting you choose. This is as easy as constructing a NumberFormatInfo properly.
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));
}
}
That's a pretty small list. I'd just setup the mappings manually.
精彩评论