Saturday, March 31, 2012

Formatting with String.Format and ToString

        static void Main()
        {
            //
            // Format a ratio as a percentage string.
            // ... You must specify the percentage symbol in the format string.
            // ... It will multiply the value by 100 for you.
            //
            double ratio = 0.73;
            string result = string.Format("string = {0:0.0%}",
                ratio);
            Console.WriteLine(result);

            int value = 123;
            string a = string.Format("{0:0000}", value); // Too complex
            string b = value.ToString("0000"); // Simpler
            Console.WriteLine(a);
            Console.WriteLine(b);

            // Format as currency
            double expense = 1234.56;
            string str = expense.ToString("C");
            Console.WriteLine("Expense: {0}", str);

            // Format with parentheses
            str = String.Format("{0:(#####0.000)}", expense);
            Console.WriteLine("Expense: {0}", str);
        }
Output:
string = 73.0%
0123
0123
Expense: $1,234.56
Expense: (1234.560)

Standard Numeric Format Strings