Using String.Format( ) and ToString( ) to Format Data


Although embedding format commands into WriteLine( ) is a convenient way to format output, sometimes you will want to create a string that contains the formatted data, but not immediately display that string. Doing so lets you format data in advance, allowing you to output it later to the device of your choosing. This is especially useful in a GUI environment such as Windows in which console-based I/O is rarely used.

In general, there are two ways to obtain the formatted string representation of a value. One way is to use String.Format( ). The other is to pass a format specifier to the ToString( ) method of the built-in numeric types. Each approach is examined here.

Using String.Format( ) to Format Values

You can obtain a formatted value by calling one of the Format( ) methods defined by String. They are shown in Table 21-5. Format( ) works much like WriteLine( ), except that it returns a formatted string rather than outputting it to the console.

Table 21-5: The Format( ) Methods

Method

Description

public static string Format(string str, object v)

Formats v according to the first format command in str. Returns a copy of str in which formatted data has been substituted for the format command.

public static string Format(string str, object v1, object v2)

Formats v1 according to the first format command in str, and v2 according to the second format command in str. Returns a copy of str in which formatted data has been substituted for the format commands.

public static string Format(string str, object v1, object v2, object v3)

Formats v1, v2, and v3 according to the corresponding format commands in str. Returns a copy of str in which formatted data has been substituted for the format commands.

public static string Format(string str, params object[ ] v)

Formats the values passed in v according to the format commands in str. Returns a copy of str in which formatted data has been substituted for each format command.

public static string Format(IFormatProvider fmtprvdr, string str, params object[ ] v)

Formats the values passed in v according to the format commands in str using the format provider specified by fmtprvdr. Returns a copy of str in which formatted data has been substituted for each format command.

Here is the previous format demonstration program rewritten to use String.Format( ). It produces the same output as the earlier version.

 // Use String.Format() to format a value. using System; class FormatDemo {   public static void Main() {     double v = 17688.65849;     double v2 = 0.15;     int x = 21;     string str = String.Format("{0:F2}", v);     Console.WriteLine(str);     str = String.Format("{0:N5}", v);     Console.WriteLine(str);     str = String.Format("{0:e}", v);     Console.WriteLine(str);     str = String.Format("{0:r}", v);     Console.WriteLine(str);     str = String.Format("{0:p}", v2);     Console.WriteLine(str);     str = String.Format("{0:X}", x);     Console.WriteLine(str);     str = String.Format("{0:D12}", x);     Console.WriteLine(str);     str = String.Format("{0:C}", 189.99);     Console.WriteLine(str);   } }

Like WriteLine( ), String.Format( ) lets you embed regular text along with format specifiers, and you can use more than one format specifier and value. For example, consider this program, which displays the running sum and product of the numbers 1 through 10:

 // A closer look at Format(). using System; class FormatDemo2 {   public static void Main() {     int i;     int sum = 0;     int prod = 1;     string str;     /* Display the running sum and product        for the numbers 1 through 10. */     for(i=1; i <= 10; i++) {       sum += i;       prod *= i;       str = String.Format("Sum:{0,3:D}  Product:{1,8:D}",                           sum, prod);       Console.WriteLine(str);     }   } }

The output is shown here:

 Sum:  1  Product:       1 Sum:  3  Product:       2 Sum:  6  Product:       6 Sum: 10  Product:      24 Sum: 15  Product:     120 Sum: 21  Product:     720 Sum: 28  Product:    5040 Sum: 36  Product:   40320 Sum: 45  Product:  362880 Sum: 55  Product: 3628800

In the program, pay close attention to this statement:

 str = String.Format("Sum:{0,3:D}  Product:{1,8:D}",                     sum, prod);

This call to Format( ) contains two format specifiers, one for sum and one for prod. Notice that the argument numbers are specified just as they are when using WriteLine( ). Also, notice that regular text, such as “Sum:” is included. This text is passed through and becomes part of the output string.

Using ToString( ) to Format Data

For all of the built-in numeric structure types, such as Int32 or Double, you can use ToString( ) to obtain a formatted string representation of the value. To do so, you will use this version of ToString( ):

 public string ToString(string fmt)

It returns the string representation of the invoking object as specified by the format specifier passed in fmt. For example, the following program creates a monetary representation of the value 188.99 through the use of the C format specifier:

 string str = 189.99.ToString("C");

Notice how the format specifier is passed directly to ToString( ). Unlike embedded format commands used by WriteLine( ) or Format( ), which supply an argument-number and field-width component, ToString( ) requires only the format specifier, itself.

Here is a rewrite of the previous format program that uses ToString( ) to obtain formatted strings. It produces the same output as the earlier versions.

 // Use ToString() to format values. using System; class ToStringDemo {   public static void Main() {     double v = 17688.65849;     double v2 = 0.15;     int x = 21;     string str = v.ToString("F2");     Console.WriteLine(str);     str = v.ToString("N5");     Console.WriteLine(str);     str = v.ToString("e");     Console.WriteLine(str);     str = v.ToString("r");     Console.WriteLine(str);     str = v2.ToString("p");     Console.WriteLine(str);     str = x.ToString("X");     Console.WriteLine(str);     str = x.ToString("D12");     Console.WriteLine(str);     str = 189.99.ToString("C");     Console.WriteLine(str);   } }




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net