C#: Format a String as Currency

As the title of this short article states, this topic is about “Currency formatting”, and I will show some examples on how to do this with C#. When producing a string for output to a customer, it is useful to format any currency value in a more human friendly money format. This is extremely easy in C#.

The standard numeric format specifier I am going to use is the Currency (“C”) Format Specifier, which is formatted like this: {0:C}

decimal price = 9565.50m;
string total = string.Format("{0:C}", price); 
Console.WriteLine(total + "\n\n"); 
Console.ReadKey();

Another way to achieve the same result is by using ToString(),

decimal price = 9565.50m;
Console.WriteLine(price.ToString("C") + "\n\n"); 
Console.ReadKey();

Result:

In addition, one can add more checks, for example, to output the value with a different currency symbol (e.g. $ £ € Lek Kr).

Using CultureInfo.CreateSpecificCulture() one can set the culture information, and thereby adjust to the country and print out the price with the proper money currency symbol.

decimal price = 9565.50m; 
string total = string.Format(CultureInfo.CreateSpecificCulture("en-GB"), "{0:C}", price);
Console.WriteLine(total + "\n\n"); 
Console.ReadKey();  

Result:

To once again show that this works, lets try with the Albanian currency format, “sq-AL”,

string total = string.Format(CultureInfo.CreateSpecificCulture("sq-AL"), "{0:C}", price);

Result:

As I said one can add more checks, I made a method which checks the culturename with a switch statement, and then formats the price string for output:

static string FormatPrice(decimal price, string cultureName)
{
   string formatted = null;
   CultureInfo info = new CultureInfo(cultureName); 
   switch (info.Name)
   { 
       case "en-US":
             formatted = string.Format(CultureInfo.CreateSpecificCulture("en-US"), 
                 "{0:C}", price);
             break; 
       case "en-GB":
             formatted = string.Format(CultureInfo.CreateSpecificCulture("en-GB"), 
                 "{0:C}", price);
             break;
       case "sq-AL":
            formatted = string.Format(CultureInfo.CreateSpecificCulture("sq-AL"), 
                "{0:C}", price);
            break;
       case "se-SE":
            formatted = string.Format(CultureInfo.CreateSpecificCulture("se-SE"), 
                "{0:C}", price);
            break; 
   }

   return formatted; 
}

This method can easily be invoked inside the Console.WriteLine() method,

decimal price = 9565.50m; 
Console.WriteLine(FormatPrice(price, "se-SE") + "\n\n"); 
Console.ReadKey(); 

Result:

Wrapping up

I’m not quite done with this, what’s really missing is real currency conversion support—for example, the ability to convert between American (USD) and European Euro (€) and vice versa. While, this tutorial and its examples are really covered to a level, this means that there’s probably more that can be added.

But for now, happy coding!