Updated: October 2008
Replaces the format item in a specified string with the string representation of a corresponding object in a specified array. A specified parameter supplies culture-specific formatting information.
Namespace:
System
Assembly:
mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
Public Shared Function Format ( _
provider As IFormatProvider, _
format As String, _
ParamArray args As Object() _
) As String
Dim provider As IFormatProvider
Dim format As String
Dim args As Object()
Dim returnValue As String
returnValue = String.Format(provider, _
format, args)
public static string Format(
IFormatProvider provider,
string format,
params Object[] args
)
public:
static String^ Format(
IFormatProvider^ provider,
String^ format,
... array<Object^>^ args
)
public static function Format(
provider : IFormatProvider,
format : String,
... args : Object[]
) : String
Return Value
Type:
System..::.StringA copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.
| Exception | Condition |
|---|
| ArgumentNullException |
format or args is nullNothingnullptra null reference (Nothing in Visual Basic). |
| FormatException |
format is invalid. -or- The index of a format item is less than zero, or greater than or equal to the length of the args array. |
This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its string representation and to embed that representation in a string. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics.
The provider parameter supplies custom and culture-specific information used to moderate the formatting process. The provider parameter is an IFormatProvider implementation whose GetFormat method is called by the String..::.Format(IFormatProvider, String, array<Object>[]()[]) method. The method must return an object to supply formatting information that is of the same type as the formatType parameter. The provider parameter's GetFormat method is called one or more times, depending on the specific type of objects in args, as follows:
It is always passed a Type object that represents the ICustomFormatter type.
It is passed a Type object that represents the DateTimeFormatInfo type for each format item whose corresponding data type is a date and time value.
It is passed a Type object that represents the NumberFormatInfo type for each format item whose corresponding data type is numeric.
For more information, see the Format Providers section of the Formatting Overview topic. The Example section provides an example of a custom format provider that outputs numeric values as customer account numbers with embedded hyphens.
The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. The formatting process replaces each format item with the string representation of the value of the corresponding object.
The syntax of a format item is as follows:
{index[,length][:formatString]}
Elements in square brackets are optional. The following table describes each element.
Element | Description |
|---|
index
| The zero-based position in the parameter list of the object to be formatted. If there is no parameter in the index position, a FormatException is thrown. If the object specified by index is nullNothingnullptra null reference (Nothing in Visual Basic), the format item is replaced by String..::.Empty. |
,length | The minimum number of characters in the string representation of the object to be formatted. If positive, the object to be formatted is right-aligned; if negative, it is left-aligned. The comma is required if length is specified. |
:formatString | A standard or custom format string that is supported by the object to be formatted. If formatString is not specified and the object to be formatted implements the IFormattable interface, nullNothingnullptra null reference (Nothing in Visual Basic) is passed as the value of the format parameter used as the IFormattable..::.ToString format string. |
The leading and trailing brace characters, '{' and '}', are required. To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".
If the value of format is, "Thank you for your purchase of {0:####} copies of Microsoft®.NET (Core Reference).", and arg[0] is an Int16 with the value 123, then the return value will be:
"Thank you for your purchase of 123 copies of Microsoft®.NET (Core Reference)."
If the value of format is, "Brad's dog has {0,-8:G} fleas.", arg[0]is an Int16 with the value 42, (and in this example, underscores represent padding spaces) then the return value will be:
"Brad's dog has 42______ fleas."
The following example demonstrates the standard formatting specifiers for numbers, dates, and enumerations. It formats the string representation of these values using the invariant culture.
' This code example demonstrates the String.Format() method.
' This example uses the provider parameter to supply formatting
' information using the invariant culture.
Imports System.Globalization
Class Sample
Public Enum Color
Yellow = 1
Blue = 2
Green = 3
End Enum 'Color
Private Shared thisDate As DateTime = DateTime.Now
Public Shared Sub Main()
' Store the output of the String.Format method in a string.
Dim s As String = ""
Console.Clear()
' Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers")
s = String.Format(CultureInfo.InvariantCulture, _
"(C) Currency: . . . . . . . . {0:C}" & vbCrLf & _
"(D) Decimal:. . . . . . . . . {0:D}" & vbCrLf & _
"(E) Scientific: . . . . . . . {1:E}" & vbCrLf & _
"(F) Fixed point:. . . . . . . {1:F}" & vbCrLf & _
"(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(N) Number: . . . . . . . . . {0:N}" & vbCrLf & _
"(P) Percent:. . . . . . . . . {1:P}" & vbCrLf & _
"(R) Round-trip: . . . . . . . {1:R}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
- 123, - 123.45F)
Console.WriteLine(s)
' Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers")
s = String.Format(CultureInfo.InvariantCulture.DateTimeFormat, _
"(d) Short date: . . . . . . . {0:d}" & vbCrLf & _
"(D) Long date:. . . . . . . . {0:D}" & vbCrLf & _
"(t) Short time: . . . . . . . {0:t}" & vbCrLf & _
"(T) Long time:. . . . . . . . {0:T}" & vbCrLf & _
"(f) Full date/short time: . . {0:f}" & vbCrLf & _
"(F) Full date/long time:. . . {0:F}" & vbCrLf & _
"(g) General date/short time:. {0:g}" & vbCrLf & _
"(G) General date/long time: . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(M) Month:. . . . . . . . . . {0:M}" & vbCrLf & _
"(R) RFC1123:. . . . . . . . . {0:R}" & vbCrLf & _
"(s) Sortable: . . . . . . . . {0:s}" & vbCrLf & _
"(u) Universal sortable: . . . {0:u} (invariant)" & vbCrLf & _
"(U) Universal full: . . . . . {0:U}" & vbCrLf & _
"(Y) Year: . . . . . . . . . . {0:Y}" & vbCrLf, _
thisDate)
Console.WriteLine(s)
' Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers")
s = String.Format(CultureInfo.InvariantCulture, _
"(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)" & vbCrLf & _
"(D) Decimal number: . . . . . {0:D}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
Color.Green)
Console.WriteLine(s)
End Sub 'Main
End Class 'Sample
'
' This example displays the following output to the console:
'
' Standard Numeric Format Specifiers
' (C) Currency: . . . . . . . . (�123.00)
' (D) Decimal:. . . . . . . . . -123
' (E) Scientific: . . . . . . . -1.234500E+002
' (F) Fixed point:. . . . . . . -123.45
' (G) General:. . . . . . . . . -123
' (default):. . . . . . . . -123 (default = 'G')
' (N) Number: . . . . . . . . . -123.00
' (P) Percent:. . . . . . . . . -12,345.00 %
' (R) Round-trip: . . . . . . . -123.45
' (X) Hexadecimal:. . . . . . . FFFFFF85
'
' Standard DateTime Format Specifiers
' (d) Short date: . . . . . . . 07/09/2007
' (D) Long date:. . . . . . . . Monday, 09 July 2007
' (t) Short time: . . . . . . . 13:42
' (T) Long time:. . . . . . . . 13:42:50
' (f) Full date/short time: . . Monday, 09 July 2007 13:42
' (F) Full date/long time:. . . Monday, 09 July 2007 13:42:50
' (g) General date/short time:. 07/09/2007 13:42
' (G) General date/long time: . 07/09/2007 13:42:50
' (default):. . . . . . . . 07/09/2007 13:42:50 (default = 'G')
' (M) Month:. . . . . . . . . . July 09
' (R) RFC1123:. . . . . . . . . Mon, 09 Jul 2007 13:42:50 GMT
' (s) Sortable: . . . . . . . . 2007-07-09T13:42:50
' (u) Universal sortable: . . . 2007-07-09 13:42:50Z (invariant)
' (U) Universal full: . . . . . Monday, 09 July 2007 20:42:50
' (Y) Year: . . . . . . . . . . 2007 July
'
' Standard Enumeration Format Specifiers
' (G) General:. . . . . . . . . Green
' (default):. . . . . . . . Green (default = 'G')
' (F) Flags:. . . . . . . . . . Green (flags or integer)
' (D) Decimal number: . . . . . 3
' (X) Hexadecimal:. . . . . . . 00000003
// This code example demonstrates the String.Format() method.
// Formatting for this example uses the "en-US" culture.
using System;
using System.Globalization;
class Sample
{
enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;
public static void Main()
{
// Store the output of the String.Format method in a string.
string s = "";
Console.Clear();
// Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers");
s = String.Format(CultureInfo.InvariantCulture,
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
Console.WriteLine(s);
// Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers");
s = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full: . . . . . {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
Console.WriteLine(s);
// Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers");
s = String.Format(CultureInfo.InvariantCulture,
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color.Green);
Console.WriteLine(s);
}
}
/*
This example displays the following output to the console:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . (�123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 07/09/2007
(D) Long date:. . . . . . . . Monday, 09 July 2007
(t) Short time: . . . . . . . 13:48
(T) Long time:. . . . . . . . 13:48:05
(f) Full date/short time: . . Monday, 09 July 2007 13:48
(F) Full date/long time:. . . Monday, 09 July 2007 13:48:05
(g) General date/short time:. 07/09/2007 13:48
(G) General date/long time: . 07/09/2007 13:48:05
(default):. . . . . . . . 07/09/2007 13:48:05 (default = 'G')
(M) Month:. . . . . . . . . . July 09
(R) RFC1123:. . . . . . . . . Mon, 09 Jul 2007 13:48:05 GMT
(s) Sortable: . . . . . . . . 2007-07-09T13:48:05
(u) Universal sortable: . . . 2007-07-09 13:48:05Z (invariant)
(U) Universal full: . . . . . Monday, 09 July 2007 20:48:05
(Y) Year: . . . . . . . . . . 2007 July
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
The following example uses the String..::.Format(IFormatProvider, String, array<Object>[]()[]) method to display the string representation of some date and time and numeric values using several different cultures.
Imports System.Globalization
Module Example
Public Sub Main()
Dim cultureNames() As String = { "en-US", "fr-FR", "de-DE", "es-ES" }
Dim dateToDisplay As Date = #9/1/2009 6:32PM#
Dim value As Double = 9164.32
Console.WriteLine("Culture Date Value")
Console.WriteLine()
For Each cultureName As String In cultureNames
Dim culture As New CultureInfo(cultureName)
Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
culture.Name, dateToDisplay, value)
Console.WriteLine(output)
Next
End Sub
End Module
' The example displays the following output:
' Culture Date Value
'
' en-US Tuesday, September 01, 2009 9,164.32
' fr-FR mardi 1 septembre 2009 9 164,32
' de-DE Dienstag, 1. September 2009 9.164,32
' es-ES martes, 01 de septiembre de 2009 9.164,32
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };
DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
double value = 9164.32;
Console.WriteLine("Culture Date Value\n");
foreach (string cultureName in cultureNames)
{
CultureInfo culture = new CultureInfo(cultureName);
string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}",
culture.Name, dateToDisplay, value);
Console.WriteLine(output);
}
}
}
// The example displays the following output:
// Culture Date Value
//
// en-US Tuesday, September 01, 2009 9,164.32
// fr-FR mardi 1 septembre 2009 9 164,32
// de-DE Dienstag, 1. September 2009 9.164,32
// es-ES martes, 01 de septiembre de 2009 9.164,32
The following example defines a customer number format provider that formats an integer value as a customer account number in the form x-xxxxx-xx.
Module TestFormatter
Public Sub Main()
Dim acctNumber As Integer = 79203159
Console.WriteLine(String.Format(New CustomerFormatter, "{0}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:G}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:S}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:P}", acctNumber))
Try
Console.WriteLine(String.Format(New CustomerFormatter, "{0:X}", acctNumber))
Catch e As FormatException
Console.WriteLine(e.Message)
End Try
End Sub
End Module
Public Class CustomerFormatter : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(type As Type) As Object _
Implements IFormatProvider.GetFormat
If type Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, _
arg As Object, _
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
If Not Me.Equals(formatProvider) Then
Return Nothing
Else
If String.IsNullOrEmpty(fmt) Then fmt = "G"
Dim customerString As String = arg.ToString()
if customerString.Length < 8 Then _
customerString = customerString.PadLeft(8, "0"c)
Select Case fmt
Case "G"
Return customerString.Substring(0, 1) & "-" & _
customerString.Substring(1, 5) & "-" & _
customerString.Substring(6)
Case "S"
Return customerString.Substring(0, 1) & "/" & _
customerString.Substring(1, 5) & "/" & _
customerString.Substring(6)
Case "P"
Return customerString.Substring(0, 1) & "." & _
customerString.Substring(1, 5) & "." & _
customerString.Substring(6)
Case Else
Throw New FormatException( _
String.Format("The '{0}' format specifier is not supported.", fmt))
End Select
End If
End Function
End Class
' The example displays the following output:
' 7-92031-59
' 7-92031-59
' 7/92031/59
' 7.92031.59
' The 'X' format specifier is not supported.
using System;
public class TestFormatter
{
public static void Main()
{
int acctNumber = 79203159;
Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
try {
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
}
catch (FormatException e) {
Console.WriteLine(e.Message);
}
}
}
public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format,
object arg,
IFormatProvider formatProvider)
{
if (! this.Equals(formatProvider))
{
return null;
}
else
{
if (String.IsNullOrEmpty(format))
format = "G";
string customerString = arg.ToString();
if (customerString.Length < 8)
customerString = customerString.PadLeft(8, '0');
format = format.ToUpper();
switch (format)
{
case "G":
return customerString.Substring(0, 1) + "-" +
customerString.Substring(1, 5) + "-" +
customerString.Substring(6);
case "S":
return customerString.Substring(0, 1) + "/" +
customerString.Substring(1, 5) + "/" +
customerString.Substring(6);
case "P":
return customerString.Substring(0, 1) + "." +
customerString.Substring(1, 5) + "." +
customerString.Substring(6);
default:
throw new FormatException(
String.Format("The '{0}' format specifier is not supported.", format));
}
}
}
}
// The example displays the following output:
// 7-92031-59
// 7-92031-59
// 7/92031/59
// 7.92031.59
// The 'X' format specifier is not supported.
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
.NET Framework
Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
.NET Compact Framework
Supported in: 3.5, 2.0, 1.0
XNA Framework
Supported in: 3.0, 2.0, 1.0
Reference
Other Resources
Date | History | Reason |
|---|
October 2008
| Expanded the Remarks section. |
Customer feedback.
|