Changes

Formatting Strings in C Sharp

1,703 bytes added, 15:59, 24 January 2008
Using Format Controls
== Using Format Controls ==
 
So far we have only substituted arguments for place holders, but we have not made any changes to the format of the arguments before they are displayed. This essentially instructs the Format() method to use the default formatting for each argument type when displaying the string. Perhaps the most powerful aspect of the Format() method is the ability to use ''format controls'' within the place holders to control the format of the output.
 
Format controls appear inside the braces ({}) of the place holders. The format of a place holder with a format control is as follows:
 
{''n'':''control''}
 
Where ''n'' is the place holder number and ''control'' is the special format control sequence to be applied to the argument.
 
== As Simple Format Control Example ==
 
The following example uses the ''X'' format control to display a number in Hexadecimal format:
 
<pre>
 
newString = String.Format("The number {0} in Hexadecimal is {0:X}", 432);
 
System.Console.WriteLine (newString);
</pre>
 
The above example displays argument 0 (the number 432) in two formats. The first is the default decimal format and the second uses the ''X'' format control to display the argument as a hexadecimal number.
 
The String.Format() method provides a wide range of format controls which are outlined in the following section.
 
== The C# String.Format() Format Controls ==
 
The following table lists format controls supported by the C# String.Format() method together with examples of each control:
 
<table>
<th>Control<th>Type<th>Description<th>Example</th>
<tr>
<td>C</td><td>Currency</td><td>Displays number prefixed with the currency simple appropriate to the current locale</td><td>{0:C} $432.00</td>
<tr>
</table>