Tuesday, May 27, 2008

Format Number As Currency String [C#.NET]

While developing web/windows applications it is very useful to display human friendly currency values as $1,345.00 instead of 1345. In C#.NET it is simple to convert a number to currency format string using the method string.format and the format item C

string.Format( "{0:C}", 123345);

Here is a fully functional sample code

class Program
{
    static void Main(string[] args)
    {
        int nPrice = 1234;
        string sString;
        //
        sString = string.Format("{0:C}", nPrice);
        //
        Console.WriteLine("Price: " + sString);
        Console.ReadLine();
    }
}

Changing the default currency symbol

If you execute the above sample code you might have seen a different currency symbol in the output other than $. The currency symbol used by string.format method depends on your operating system's regional settings. For instance if you are running the code on a OS configured with Indian regional settings you would have seen the output as Rs. 1,235.00.

If required you can change the currency to be used by String.Format method with the help of NumberFormatInfo class. Here is a sample code that forces string.format to use Pound as currency sign

System.Globalization.NumberFormatInfo nfi;
nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "£";
sString = string.Format(nfi, "{0:C}", 123345);

1 Comment:

Anonymous said...

can u help me. The Req'ed out put format: 1,23,45,67,890.00