Type System.IFormattable

Variables:
Constructors:
Functions:

public System.String ToString(System.String format, System.IFormatProvider formatProvider)

Returns a System.String representation of the value of the current instance.

Parameter format: A System.String that specifies the format of the returned string. If format is a null reference or the empty string, the default format defined for the type of the current instance is used.

Parameter formatProvider: A System.IFormatProvider that supplies a formatting object containing culture-specific formatting information, or null .

Returns: A System.String containing the value of the current instance formatted in accordance with format and formatProvider .

Throws: : The specified format is invalid or cannot be used with the type of the current instance.

Conforming implementations do not throw an exception when format and/or formatProvider are null references. If formatProvider is a null reference, the string is constructed using a system-supplied formatting object containing information for the current system culture. If format is null, the string is constructed using a system-supplied default format appropriate for the type of the current instance. If the object returned by formatProvider supplies a culture-specific representation of symbols or patterns included in format, the returned string is required to use the information supplied by formatProvider . Implement to allow consumers of a class to use format strings and formatting objects to control the way in which the class is represented as a string.

Example:

The following example demonstrates using the System.IFormattable.ToString(System.String,System.IFormatProvider) method to display values in a variety of formats. The current system culture is U.S. English, which provides the default values for the formatProvider parameter of System.IFormattable.ToString(System.String,System.IFormatProvider).

using System;
class FormattableExample {
    public static void Main() {
    double d = 123.12345678901234;
    string[] formats = {"C","E","e","F","G","N","P","R"};
    for (int i = 0; i< formats.Length;i++) 
        Console.WriteLine("{0:R} as {1}:  {2}",d,formats[i],d.ToString(formats[i],null));

    string[]intFormats = {"D","x","X"};
    int val = 255;
    for (int i = 0; i< intFormats.Length;i++) 
        Console.WriteLine("{0} as {1}:  {2}",val,intFormats[i],val.ToString(intFormats[i],null));

    }
}

The output is

123.12345678901234 as C: $123.12

123.12345678901234 as E: 1.231235E+002

123.12345678901234 as e: 1.231235e+002

123.12345678901234 as F: 123.12

123.12345678901234 as G: 123.123456789012

123.12345678901234 as N: 123.12

123.12345678901234 as P: 12,312.35 %

123.12345678901234 as R: 123.12345678901234

255 as D: 255

255 as x: ff

255 as X: FF