Monday, August 10, 2009

Format Number As Currency String [C#.NET]

While in the Web Development / Windows applications, it is very helpful to the friendly currency values as $ 1345.00 instead of 1345. In C #. NET, it is easy to set up a series of string format, the currency with the method and the string.Format 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();
        }
    }

Output
Price=$123,345.00

Change the default currency symbol

If you use the code example above, you may have a different icon in production than $. The symbol of string.Format depends on your operating system locale. For example, if the code of an operating system, configured with the regional Indian you have the result in R. 1235.00.

If necessary, you can set the currency to use string.Format by using NumberFormatException Info class. Here is an example that forces string.Format Pound as a currency symbol

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

Output
Price=£123,345.00

No comments:

Post a Comment