Search code examples
c#currencycultureinforegioninfo

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?


Solution

  • 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