JP Hellemons
JP Hellemons

Reputation: 6047

Currency format C# ISOCurrencySymbol

I would normally just use this:

double test = 1234.5678;
Console.WriteLine(test.ToString("C"));

which works great. I had an "overwrite" for canadian dollars to make sure that people would see the difference between US and Canadian dollars:

var canadaFi = (NumberFormatInfo)CultureInfo.GetCultureInfo("en-CA").NumberFormat.Clone();
canadaFi.CurrencySymbol = "C$ ";
Console.WriteLine(val.ToString("C", canadaFi));

But now people are asking output like:

CAD 1234,56

So I used:

RegionInfo ca = new RegionInfo("en-CA");
Console.WriteLine(string.Format("{0} {1}", ca.ISOCurrencySymbol, test.ToString("f2")));

which works, but I am wondering if this is the best approach to get the 3 char iso currency symbol in front of the float/double. So instead of using the CultureInfo I have to use RegionInfo now?

Upvotes: 2

Views: 3197

Answers (2)

abto
abto

Reputation: 1628

The correct way would be:

const string canada = "en-CA";

var ca = new RegionInfo(canada);
var cai = new CultureInfo(canada)
{
    NumberFormat =
    {
        CurrencySymbol = ca.ISOCurrencySymbol,
        CurrencyPositivePattern = 2,
        CurrencyNegativePattern = 12
    }
};

Console.WriteLine(test.ToString("C", cai));

If you set CurrencyPositivePattern = 2 you make sure, the symbol is placed in front of the number with an additional empty space (see also documentation for CurrencyPositivePattern), CurrencyNegativePattern = 12 does the same for negative values (documentation for CurrencyNegativePattern).

output:

CAD 1,234.57

and for negative

CAD -1,234.57

Upvotes: 3

JP Hellemons
JP Hellemons

Reputation: 6047

as @Corak explains:

CultureInfo cai = new CultureInfo("en-CA");
RegionInfo ca = new RegionInfo("en-CA");
Console.WriteLine(ca.ISOCurrencySymbol + " " + test.ToString("C", cai).Substring(1));

output:

CAD 1,234.57

@Coraks suggestion added:

Console.WriteLine(ca.ISOCurrencySymbol + " " + test.ToString("C", cai).Replace(cai.CurrencySymbol, ""));

Upvotes: 0

Related Questions