String..::.Format Method (String, Object)
This page is specific to:.NET Framework Version:
.NET Framework Class Library
String..::.Format Method (String, Object)

Updated: December 2009

Replaces one or more format items in a specified string with the string representation of a specified object.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Syntax

'Usage

Dim format As String
Dim arg0 As Object
Dim returnValue As String

returnValue = String.Format(format, _
    arg0)

'Declaration

Public Shared Function Format ( _
    format As String, _
    arg0 As Object _
) As String

Parameters

format
Type: System..::.String
A composite format string.
arg0
Type: System..::.Object
An object to format.

Return Value

Type: System..::.String
A copy of format in which any format items are replaced by the string representation of arg0.
Exceptions

ExceptionCondition
ArgumentNullException

format is nullNothingnullptra null reference (Nothing in Visual Basic).

FormatException

The format item in format is invalid.

-or-

The index of a format item is greater or less than zero.

Remarks

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 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 the object specified by index is nullNothingnullptra null reference (Nothing in Visual Basic), the format item is replaced by String..::.Empty. Because this overload has only a single object in its parameter list, the value of index must always be 0. If there is no parameter in the index position, a FormatException is thrown.

,length

The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.

:formatString

A standard or custom format string that is supported by the parameter.

NoteNote:

For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the standard format strings used with enumerations, see Enumeration Format Strings.

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 "}}".

Although the String..::.Format(String, Object) method has a single object in the parameter list, format can include more than one format item as long as each has the same index. In the following example, the format string includes two format items: one displays the decimal value of a number and the other displays its hexadecimal value.

Module Example
   Public Sub Main()
      Dim values() As Short = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue }
      Console.WriteLine("{0,10}  {1,10}", "Decimal", "Hex")
      Console.WriteLine()
      For Each value As Short In values
         Dim formatString As String = String.Format("{0,10:G}: {0,10:X}", value)
         Console.WriteLine(formatString)
      Next        
   End Sub
End Module
' The example displays the following output:
'       Decimal         Hex
'    
'        -32768:       8000
'           -27:       FFE5
'             0:          0
'          1042:        412
'         32767:       7FFF


If the value of format is, "Thank you for your purchase of {0:####} copies of Microsoft®.NET (Core Reference).", and arg0 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.", arg0 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."

Examples

The following example uses the Format(String, Object) method to embed an individual's age in the middle of a string.

Module Example
   Public Sub Main()
      Dim birthdate As Date = #7/28/1993#
      Dim dates() As Date = { #9/16/1993#, #7/28/1994#, #10/16/2000#, _
                              #7/27/2003#, #5/27/2007# }
      For Each dateValue As Date In dates
         Dim interval As TimeSpan = dateValue - birthdate
         ' Get the approximate number of years, without accounting for leap years.
         Dim years As Integer = CInt(interval.TotalDays) \ 365
         ' See if adding the number of years exceeds dateValue.
         Dim output As String
         If birthdate.AddYears(years) <= dateValue Then
            output = String.Format("You are now {0} years old.", years)
            Console.WriteLine(output)
         Else
            output = String.Format("You are now {0} years old.", years - 1)
            Console.WriteLine(output)   
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       You are now 0 years old.
'       You are now 1 years old.
'       You are now 7 years old.
'       You are now 9 years old.
'       You are now 13 years old.


Platforms

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.
Version Information

.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
See Also

Reference

Other Resources

Change History

Date

History

Reason

December 2009

Replaced the example.

Customer feedback.

October 2008

Expanded the Remarks section.

Customer feedback.

Community Content

What about {0.0} and {#.#}
Added by:CodeDreamer68

May I suggest adding example code similar to the following:

String.Format("(##.##): {0:##.##} {1:##.##} {2:##.##} {3:##.##} {4:##.##} {5:##.##}", 0.1, 1.2, 1, 1.234, 123.45, 123.456)


which results in:


(##.##): .1 1.2 1 1.23 123.45 123.46

...And...


String.Format("(00.00): {0:00.00} {1:00.00} {2:00.00} {3:00.00} {4:00.00} {5:00.00}", 0.1, 1.2, 1, 1.234, 123.45, 123.456)


Which would result in:


(00.00): 00.10 01.20 01.00 01.23 123.45 123.46

String Formatting - using PowerShell
Added by:Thomas Lee
<#  

.SYNOPSIS

Demonstrates simple string formatting using Powershell

.DESCRIPTION

This script formats 5 numbers in Decimal, Hex and Currency and is

an adaptation of the C# sample in the MSDN Library

.NOTES

Author : Thomas Lee - tfl@psp.co.uk

.LINK

http:////msdn.microsoft.com/en-us/library/fht0f5be.aspx

http://www.pshscripts.blogspot.com

.EXAMPLE

PS C:\foo> .\Get-StringFormat1.ps1

Decimal Hex Currency

-32768: 8000 ($32,768.00)

-27: FFFFFFE5 ($27.00)

0: 0 $0.00

1042: 412 $1,042.00

32767: 7FFF $32,767.00

#>

# Create an array of values to display

$values = [Int16]::MinValue, -27, 0, 1042, [Int16]::maxValue


# Print header line then values

"{0,10} {1,10} {2,14}" -f "Decimal", "Hex", "Currency"

foreach ($value in $values) {

"{0,10:G}: {0,10:X} {0,14:C}" -f $value

}

Formating with PowerShell - second sample
Added by:Thomas Lee
  
<#
.SYNOPSIS
Demonstrates string formatting using Powershell
.DESCRIPTION
This script formats 2 numbers in a variety of ways, also
formats an enum.
An adaptation of the C# sample in the MSDN Library. However,
this script uses a built-in enum, and displays two.
.NOTES
Author : Thomas Lee - tfl@psp.co.uk
.INPUTTYPE
This script has no effective parameters.
.RETURNVALUE
This script produces output as shown in the example
.LINK
http:////msdn.microsoft.com/en-us/library/fht0f5be.aspx
http://www.pshscripts.blogspot.com
.EXAMPLE
PS C:\foo> .\'Get-StringFormat2.ps1'
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Date Format
(d) Short date: . . . . . . . 12/25/2008
(D) Long date:. . . . . . . . Thursday, December 25, 2008
(t) Short time: . . . . . . . 2:12 PM
(T) Long time:. . . . . . . . 2:12:55 PM
(f) Full date/short time: . . Thursday, December 25, 2008 2:12 PM
(F) Full date/long time:. . . Thursday, December 25, 2008 2:12:55 PM
(g) General date/short time:. 12/25/2008 2:12 PM
(G) General date/long time: . 12/25/2008 2:12:55 PM
(default):. . . . . . . . 12/25/2008 2:12:55 PM
(M) Month:. . . . . . . . . . December 25
(R) RFC1123:. . . . . . . . . Thu, 25 Dec 2008 14:12:55 GMT
(s) Sortable: . . . . . . . . 2008-12-25T14:12:55
(u) Universal sortable: . . . 2008-12-25 14:12:55Z
(U) Universal full date/time: Thursday, December 25, 2008 2:12:55 PM
(Y) Year: . . . . . . . . . . December, 2008
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green
(F) Flags:. . . . . . . . . . Green
(D) Decimal number: . . . . . 79
(X) Hexadecimal:. . . . . . . 0000004F
Standard Enumeration Format Specifiers (again)
(G) General:. . . . . . . . . Gainsboro
(default):. . . . . . . . Gainsboro
(F) Flags:. . . . . . . . . . Gainsboro
(D) Decimal number: . . . . . 74
(X) Hexadecimal:. . . . . . . 0000004A
.EXAMPLE
PS C:\Users\tfl> Get-Help .\Get-StringFormat2.ps1'
Left as an exercise for the reader.
#>
##
# Start of script
##
#Format a negative integer or floating-point number in various ways.
"Standard Numeric Format Specifiers"
"(C) Currency: . . . . . . . . {0:C}" -f -123
"(D) Decimal:. . . . . . . . . {0:D}" -f -123
"(E) Scientific: . . . . . . . {0:E}" -f -123.45
"(F) Fixed point:. . . . . . . {0:F}" -f -123.45
"(G) General:. . . . . . . . . {0:G}" -f -123
"(default):. . . . . . . . {0} " -f -123
"(N) Number: . . . . . . . . . {0:N}" -f -123
"(P) Percent:. . . . . . . . . {0:P}" -f -123.45
"(R) Round-trip: . . . . . . . {0:R}" -f -123.45
"(X) Hexadecimal:. . . . . . . {0:X}" -f -123
""
# Format the current date in various ways.
$today = Get-Date
"Date Format"
"(d) Short date: . . . . . . . {0:d}" -f $today
"(D) Long date:. . . . . . . . {0:D}" -f $today
"(t) Short time: . . . . . . . {0:t}" -f $today
"(T) Long time:. . . . . . . . {0:T}" -f $today
"(f) Full date/short time: . . {0:f}" -f $today
"(F) Full date/long time:. . . {0:F}" -f $today
"(g) General date/short time:. {0:g}" -f $today
"(G) General date/long time: . {0:G}" -f $today
" (default):. . . . . . . . {0} " -f $today
"(M) Month:. . . . . . . . . . {0:M}" -f $today
"(R) RFC1123:. . . . . . . . . {0:R}" -f $today
"(s) Sortable: . . . . . . . . {0:s}" -f $today
"(u) Universal sortable: . . . {0:u}" -f $today
"(U) Universal full date/time: {0:U}" -f $today
"(Y) Year: . . . . . . . . . . {0:Y}" -f $today
""
# Format a Color enumeration value in various ways.
"Standard Enumeration Format Specifiers"
"(G) General:. . . . . . . . . {0:G}" -f [system.Drawing.KnownColor]::Green
" (default):. . . . . . . . {0}" -f [system.Drawing.KnownColor]::Green
"(F) Flags:. . . . . . . . . . {0:F} " -f [system.Drawing.KnownColor]::Green
"(D) Decimal number: . . . . . {0:D} " -f [system.Drawing.KnownColor]::Green
"(X) Hexadecimal:. . . . . . . {0:X}" -f [system.Drawing.KnownColor]::Green
"Standard Enumeration Format Specifiers (again)"
"(G) General:. . . . . . . . . {0:G}" -f [system.Drawing.KnownColor]::Gainsboro
" (default):. . . . . . . . {0}" -f [system.Drawing.KnownColor]::Gainsboro
"(F) Flags:. . . . . . . . . . {0:F} " -f [system.Drawing.KnownColor]::Gainsboro
"(D) Decimal number: . . . . . {0:D} " -f [system.Drawing.KnownColor]::Gainsboro
"(X) Hexadecimal:. . . . . . . {0:X}" -f [system.Drawing.KnownColor]::Gainsboro
### End of Script
# Format the curre
© 2010 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View