Displaying Currency In Country’s Local Format
November 3, 2010 by UberMonkey · Leave a Comment
While working on a project that needed to display the currency of an item for sale in the country’s local format, I came across a nice and simple way to handle it. Some might think of making a nice big old if/else or switch, and rolling your own formatting for each country. The way I found was some what similar, but taking advantage of the ToString function of the SalePrice variable, which happened to be a float.
The following will format the float to your current country’s currency format:
float salePrice = 20.5f;
string salePriceString = salePrice.ToString("C");
Console.WriteLine(salePriceString);
For US, it should output $20.50 as the salePriceString.
Now to handle other countries, there is a nice overload for ToString, which allows you to pass in the CultureInfo.
Here is how to output the same value formatted for Great Britain Pounds:
float salePrice = 20.5f;
string salePriceString = salePrice.ToString("C", new CultureInfo("en-GB"));
Console.WriteLine(salePriceString);
Simple enough, no? This doesn’t do any currency conversions, but it does format the float into a correct currency string.