Export (0) Print
Expand All

String.Format Method

Replaces each format item in a specified string with the text equivalent of a corresponding object's value.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method Static member Format(String, Object) Replaces one or more format items in a specified string with the string representation of a specified object.
Public method Static member Format(String, Object()) Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
Public method Static member Format(IFormatProvider, String, Object()) Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.
Public method Static member Format(String, Object, Object) Replaces the format items in a specified string with the string representation of two specified objects.
Public method Static member Format(String, Object, Object, Object) Replaces the format items in a specified string with the string representation of three specified objects.
Top

In this section:

Overloaded method syntax
Parameters
Return value
Exceptions
Which method do I call?
The Format method in brief
The Format item
How arguments are formatted
Format items that have the same index
Formatting and culture
Custom formatting operations
Examples:
       Formatting a single argument
       Formatting two arguments
       Formatting three arguments
       Formatting more than three arguments
       Culture-sensitive formatting
       A custom formatting operation
       An intercept provider and Roman numeral formatter
Version information
String.Format Q & A

Overloaded method syntax

For additional guidance on choosing an overload, see Which method do I call?

String String.Format(String format , Object arg0 )

Replaces the format items with the string representation of a specified object (example).

String String.Format(String format , Object arg0 , Object arg1 )

Replaces the format items with the string representation of two specified objects (example).

String String.Format(String format , Object arg0 , Object arg1 , Object arg2 )

Replaces the format items with the string representation of three specified objects (example).

String String.Format(String format , params Object[] args )

Replaces the format items with the string representations of corresponding objects in a specified array (example).

String String.Format(IFormatProvider provider , String format , params Object[] args )

Replaces the format items with the string representation of corresponding objects in a specified array, and uses the specified culture-specific formatting information (example) or custom formatting information (example).

Parameters

This is a complete list of parameters for the Format method; see the overload syntax above for the parameters used by each overload. Only the format parameter is used by all overloads.

Parameter

Type

Description

s

String

A composite format string that includes one or more format items (see The format item).

arg0

String

The first or only object to format.

arg1

String

The second object to format.

arg2

String

The third object to format.

args

String []

Zero or more objects to format, supplied either in a comma-delimited list or as an array.

provider

IFormatProvider

An object that supplies custom or culture-specific formatting information.

Return value

Type: String
A copy of format in which the format items have been replaced by the string representations of the corresponding arguments.

Exceptions

Exception

Condition

Thrown by

ArgumentNullException

format is Nothing.

All overloads.

FormatException

format is invalid.

-or-

The index of a format item is less than zero, or greater than or equal to the number of arguments in the arguments list.

All overloads.

Which method do I call?

To

Call

Format one or more objects by using the conventions of the current culture.

Except for the overload that includes a provider parameter, all Format overloads include a String parameter followed by one or more object parameters. Because of this, you do not have to determine which Format overload you intend to call. Your language compiler will select the appropriate overload from among the overloads that don't have a provider parameter, based on your argument list. For example, if your argument list has five arguments, the compiler will call the Format(String, Object()) method.

Format one or more objects by using the conventions of a specific culture.

Format(IFormatProvider, String, Object())

Perform a custom formatting operation either with an ICustomFormatter implementation or an IFormattable implementation.

Format(IFormatProvider, String, Object())

The Format method in brief

Each overload of the Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is Nothing, the format item is replaced with String.Empty. For example, the following call to the Format(String, Object, Object, Object) method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items.

Dim dat As Date = #1/17/2012 9:30AM# 
Dim city As String = "Chicago" 
Dim temp As Integer = -16
Dim output As String = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                                     dat, city, temp)
Console.WriteLine(output)
' The example displays the following output: 
'    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   

The format item

A format item has this syntax:

{ index[,alignment][ :formatString] }

Brackets denote optional elements. The opening and closing braces are required. (To include a literal opening or closing brace in the format string, see the "Escaping Braces" section in the Composite Formatting article.)

For example, a format item to format a currency value might appears like this:

String.Format("{0,-10:C}", 126347.89d)        

A format item has the following elements:

index

The zero-based index of the argument whose string representation is to be included at this position in the string. If this argument is Nothing, an empty string will be included at this position in the string.

alignment

Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.

formatString

Optional. A string that specifies the format of the corresponding argument's result string. If you omit formatString, the corresponding argument's parameterless ToString method is called to produce its string representation. If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. Types that support format strings include:

However, note that any custom type can implement IFormattable or extend an existing type's IFormattable implementation.

The following example uses the alignment and formatString arguments to produce formatted output.

Module Example
   Public Sub Main()
      ' Create array of 5-tuples with population data for three U.S. cities, 1940-1950. 
      Dim cities()  = _
          { Tuple.Create("Los Angeles", #1/1/1940#, 1504277, #1/1/1950#, 1970358),
            Tuple.Create("New York", #1/1/1940#, 7454995, #1/1/1950#, 7891957),  
            Tuple.Create("Chicago", #1/1/1940#, 3396808, #1/1/1950#, 3620962),  
            Tuple.Create("Detroit", #1/1/1940#, 1623452, #1/1/1950#, 1849568) }

      ' Display header 
      Dim header As String = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}",
                                           "City", "Year", "Population", "Change (%)")
      Console.WriteLine(header)
      Console.WriteLine()
      Dim output As String       
      For Each city In cities
         output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/city.Item3)
         Console.WriteLine(output)
      Next 
   End Sub 
End Module 
' The example displays the following output: 
'    City            Year  Population    Year  Population    Change (%) 
'     
'    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 % 
'    New York        1940   7,454,995    1950   7,891,957         5.9 % 
'    Chicago         1940   3,396,808    1950   3,620,962         6.6 % 
'    Detroit         1940   1,623,452    1950   1,849,568        13.9 %

How arguments are formatted

Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The Format method retrieves the argument and derives its string representation as follows:

For an example that intercepts calls to the ICustomFormatter.Format method and allows you to see what information the Format method passes to a formatting method for each format item in a composite format string, see Example 7: An intercept provider and Roman numeral formatter.

Format items that have the same index

The Format method throws a FormatException exception if the index of an index item is greater than or equal to the number of arguments in the argument list. However, format can include more format items than there are arguments, as long as multiple format items have the same index. In the call to the Format(String, Object) method in following example, the argument list has a single argument, but 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

Formatting and culture

Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the CultureInfo.CurrentCulture property. You can control this behavior by calling the Format(IFormatProvider, String, Object()) overload. This overload's provider parameter is an IFormatProvider implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process.

The IFormatProvider interface has a single member, GetFormat, which is responsible for returning the object that provides formatting information. The .NET Framework has three IFormatProvider implementations that provide culture-specific formatting:

Custom formatting operations

You can also call the Format(IFormatProvider, String, Object()) overload to perform custom formatting operations. For example, you could format an integer as an identification number or as a telephone number. To perform custom formatting, your provider argument must implement both the IFormatProvider and ICustomFormatter interfaces. When the Format(IFormatProvider, String, Object()) method is passed an ICustomFormatter implementation as the provider argument, the Format method calls its IFormatProvider.GetFormat implementation and requests an object of type ICustomFormatter. It then calls the returned ICustomFormatter object's Format method to format each format item in the composite string passed to it.

For more information about providing custom formatting solutions, see How to: Define and Use Custom Numeric Format Providers and ICustomFormatter. For an example that converts integers to formatted custom numbers, see Example 6: A custom formatting operation. For an example that converts unsigned bytes to Roman numerals, see Example 7: An intercept provider and Roman numeral formatter.

Example 1: Formatting a single argument

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.

Example 2: Formatting two arguments

This example uses the Format(String, Object, Object) method to display time and temperature data stored in a generic Dictionary(Of TKey, TValue) object. Note that the format string has three format items, although there are only two objects to format. This is because the first object in the list (a date and time value) is used by two format items: The first format item displays the time, and the second displays the date.

Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim temperatureInfo As New Dictionary(Of Date, Double) 
      temperatureInfo.Add(#6/1/2010 2:00PM#, 87.46)
      temperatureInfo.Add(#12/1/2010 10:00AM#, 36.81)

      Console.WriteLine("Temperature Information:")
      Console.WriteLine()
      Dim output As String    
      For Each item In temperatureInfo
         output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", _
                                item.Key, item.Value)
         Console.WriteLine(output)
      Next 
   End Sub 
End Module 
' The example displays the following output: 
'       Temperature Information: 
'        
'       Temperature at  2:00 PM on  6/1/2010:  87.5°F 
'       Temperature at 10:00 AM on 12/1/2010:  36.8°F

Example 3: Formatting three arguments

This example uses the Format(String, Object, Object, Object) method to create a string that illustrates the result of a Boolean And operation with two integer values. Note that the format string includes six format items, but the method has only three items in its parameter list, because each item is formatted in two different ways.

Public Module Example
   Public Sub Main()
      Dim formatString As String = "    {0,10} ({0,8:X8})" + vbCrLf +  _
                                   "And {1,10} ({1,8:X8})" + vbCrLf + _
                                   "  = {2,10} ({2,8:X8})" 
      Dim value1 As Integer = 16932
      Dim value2 As Integer = 15421
      Dim result As String = String.Format(formatString, _
                                           value1, value2, value1 And value2)
      Console.WriteLine(result)                          
   End Sub 
End Module 
' The example displays the following output: 
'                16932 (00004224) 
'       And      15421 (00003C3D) 
'         =         36 (00000024)

Example 4: Formatting more than three arguments

This example creates a string that contains data on the high and low temperature on a particular date. The composite format string has five format items in the C# example and six in the Visual Basic example. Two of the format items define the width of their corresponding value's string representation, and the first format item also includes a standard date and time format string.

Module Example
   Public Sub Main()
      Dim date1 As Date = #7/1/2009#
      Dim hiTime As New TimeSpan(14, 17, 32)
      Dim hiTemp As Decimal = 62.1d 
      Dim loTime As New TimeSpan(3, 16, 10)
      Dim loTemp As Decimal = 54.8d 

      Dim result1 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                           date1, hiTime, hiTemp, loTime, loTemp, vbCrLf)
      Console.WriteLine(result1)
      Console.WriteLine()

      Dim result2 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                            New Object() { date1, hiTime, hiTemp, loTime, loTemp, vbCrLf })
      Console.WriteLine(result2)                                            
   End Sub 
End Module 
' The example displays the following output: 
'       Temperature on 7/1/2009: 
'          14:17:32: 62.1 degrees (hi) 
'          03:16:10: 54.8 degrees (lo) 

'       Temperature on 7/1/2009: 
'          14:17:32: 62.1 degrees (hi) 
'          03:16:10: 54.8 degrees (lo)

You can also pass the objects to be formatted as an array rather than a an argument list.

Public Class CityInfo
   Public Sub New(name As String, population As Integer, area As Decimal, year As Integer)
      Me.Name = name
      Me.Population = population
      Me.Area = area
      Me.Year = year
   End Sub 

   Public ReadOnly Name As String 
   Public ReadOnly Population As Integer 
   Public ReadOnly Area As Decimal 
   Public ReadOnly Year As Integer 
End Class 

Module Example
   Public Sub Main()
      Dim nyc2010 As New CityInfo("New York", 8175133, 302.64d, 2010)
      ShowPopulationData(nyc2010)
      Dim sea2010 As New CityInfo("Seattle", 608660, 83.94d, 2010)      
      ShowPopulationData(sea2010) 
   End Sub 

   Private Sub ShowPopulationData(city As CityInfo)
      Dim args() As Object = { city.Name, city.Year, city.Population, city.Area }
      Dim result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
      Console.WriteLine(result) 
   End Sub 
End Module 
' The example displays the following output: 
'       New York in 2010: Population 8,175,133, Area 302.6 sq. feet 
'       Seattle in 2010: Population 608,660, Area 83.9 sq. feet   

Example 5: Culture-sensitive formatting

This example uses the Format(IFormatProvider, String, Object()) method to display the string representation of some date and time values and numeric values by 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

Example 6: A custom formatting operation

This example defines a 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.

Example 7: An intercept provider and Roman numeral formatter

This example defines a custom format provider that implements the ICustomFormatter and IFormatProvider interfaces to do two things:

  • It displays the parameters passed to its ICustomFormatter.Format implementation. This enables us to see what parameters the Format(IFormatProvider, String, Object()) method is passing to the custom formatting implementation for each object that it tries to format. This can be useful when you're debugging your application.

  • If the object to be formatted is an unsigned byte value that is to be formatted by using the "R" standard format string, the custom formatter formats the numeric value as a Roman numeral.

Imports System.Globalization

Public Class InterceptProvider : Implements IFormatProvider, ICustomFormatter
   Public Function GetFormat(formatType As Type) As Object _
         Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then 
         Return Me 
      Else 
         Return Nothing 
      End If 
   End Function 

   Public Function Format(fmt As String, obj As Object, provider As IFormatProvider) As String _
         Implements ICustomFormatter.Format

      Dim formatString As String = If(fmt IsNot Nothing, fmt, "<null>")
      Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
                        provider, If(obj IsNot Nothing, obj, "<null>"), formatString)

      If obj Is Nothing Then Return String.Empty

      ' If this is a byte and the "R" format string, format it with Roman numerals. 
      If TypeOf(obj) Is Byte AndAlso formatString.ToUpper.Equals("R") Then 
         Dim value As Byte = CByte(obj)
         Dim remainder As Integer 
         Dim result As Integer 
         Dim returnString As String = String.Empty

         ' Get the hundreds digit(s)
         result = Math.DivRem(value, 100, remainder)
         If result > 0 Then returnString = New String("C"c, result)
         value = CByte(remainder)
         ' Get the 50s digit
         result = Math.DivRem(value, 50, remainder)
         If result = 1 Then returnString += "L"
         value = CByte(remainder)
         ' Get the tens digit.
         result = Math.DivRem(value, 10, remainder)
         If result > 0 Then returnString += New String("X"c, result)
         value = CByte(remainder) 
         ' Get the fives digit.
         result = Math.DivRem(value, 5, remainder)
         If result > 0 Then returnString += "V"
         value = CByte(remainder)
         ' Add the ones digit. 
         If remainder > 0 Then returnString += New String("I"c, remainder)

         ' Check whether we have too many X characters. 
         Dim pos As Integer = returnString.IndexOf("XXXX")
         If pos >= 0 Then 
            Dim xPos As Integer = returnString.IndexOf("L") 
            If xPos >= 0 And xPos = pos - 1 Then
               returnString = returnString.Replace("LXXXX", "XC")
            Else
               returnString = returnString.Replace("XXXX", "XL")   
            End If          
         End If 
         ' Check whether we have too many I characters
         pos = returnString.IndexOf("IIII")
         If pos >= 0 Then 
            If returnString.IndexOf("V") >= 0 Then
               returnString = returnString.Replace("VIIII", "IX")
            Else
               returnString = returnString.Replace("IIII", "IV")    
            End If 
         End If 
         Return returnString 
      End If    

      ' Use default for all other formatting. 
      If obj Is GetType(IFormattable)
         Return CType(obj, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
      Else 
         Return obj.ToString()
      End If 
   End Function 
End Class 

Module Example
   Public Sub Main()
      Dim n As Integer = 10
      Dim value As Double = 16.935
      Dim day As DateTime = Date.Now
      Dim provider As New InterceptProvider()
      Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}", n, value, day))
      Console.WriteLine()
      Console.WriteLine(String.Format(provider, "{0}: {1:F}", "Today", 
                                      CType(Date.Now.DayOfWeek, DayOfWeek)))
      Console.WriteLine()
      Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n", 
                                      CByte(2), CByte(12), CByte(199)))
      Console.WriteLine()
      Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}", 
                                      CByte(2), CByte(12), CByte(199)))
   End Sub 
End Module 
' The example displays the following output: 
'    Provider: InterceptProvider, Object: 10, Format String: N0 
'    Provider: InterceptProvider, Object: 16.935, Format String: C2 
'    Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d 
'    10: $16.94 on 1/31/2013 
'     
'    Provider: InterceptProvider, Object: Today: , Format String: <null> 
'    Provider: InterceptProvider, Object: Thursday, Format String: F 
'    Today: : Thursday 
'     
'    Provider: InterceptProvider, Object: 2, Format String: X 
'    Provider: InterceptProvider, Object: 12, Format String: <null> 
'    Provider: InterceptProvider, Object: 199, Format String: <null> 
'    2, 12, 199 
'     
'    Provider: InterceptProvider, Object: 2, Format String: R 
'    Provider: InterceptProvider, Object: 12, Format String: R 
'    Provider: InterceptProvider, Object: 199, Format String: R 
'    II, XII, CXCIX

Version information

.NET Framework

All overloads are supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

All overloads are supported in: 4, 3.5 SP1

Portable Class Library

Only Format(String, Object()) and Format(IFormatProvider, String, Object()) are supported

.NET for Windows Store apps

Only Format(String, Object()) and Format(IFormatProvider, String, Object()) are supported in Windows 8

String.Format Q & A

The general syntax of a format item is:

{index[,alignment][: formatString]}

where alignment is a signed integer that defines the field width. If this value is negative, text in the field is left-aligned. If it is positive, text is right-aligned.

All standard numeric format strings except "D" (which is used with integers only), "G", "R", and "X" allow a precision specifier that defines the number of decimal digits in the result string. The following example uses standard numeric format strings to control the number of decimal digits in the result string.

Module Example
   Public Sub Main()
      Dim values() As Object = { 1603, 1794.68235, 15436.14 }
      Dim result As String 
      For Each value In values
         result = String.Format("{0,12:C2}   {0,12:E3}   {0,12:F4}   {0,12:N3}  {1,12:P2}",
                                value, CDbl(value) / 10000)
         Console.WriteLine(result) 
         Console.WriteLine()
      Next                              
   End Sub 
End Module 
' The example displays the following output: 
'       $1,603.00     1.603E+003      1603.0000      1,603.000       16.03 % 
'     
'       $1,794.68     1.795E+003      1794.6824      1,794.682       17.95 % 
'     
'      $15,436.14     1.544E+004     15436.1400     15,436.140      154.36 %

If you're using a custom numeric format string, use the "0" format specifier to control the number of decimal digits in the result string, as the following example shows.

Module Example
   Public Sub Main()
      Dim value As Decimal = 16309.5436d
      Dim result As String = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}", 
                                           value)
      Console.WriteLine(result)
   End Sub 
End Module 
' The example displays the following output: 
'    16309.54360    16,309.54    16309.544

By default, formatting operations only display non-zero integral digits. If you are formatting integers, you can use a precision specifier with the "D" and "X" standard format strings to control the number of digits.

Module Example
   Public Sub Main()
      Dim value As Integer = 1326
      Dim result As String = String.Format("{0,10:D6} {0,10:X8}", value)
      Console.WriteLine(result)
   End Sub 
End Module 
' The example displays the following output: 
'       001326   0000052E

You can pad an integer or floating-point number with leading zeros to produce a result string with a specified number of integral digits by using the "0" custom numeric format specifier, as the following example shows.

Module Example
   Public Sub Main()
      Dim value As Integer = 16342
      Dim result As String = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}", 
                                           value)
      Console.WriteLine(result)
   End Sub 
End Module 
' The example displays the following output: 
'           00016342       00016342.000    0,000,016,342.0

There is no practical limit. The second parameter of the Format(IFormatProvider, String, Object()) method is tagged with the ParamArrayAttribute attribute, which allows you to include either a delimited list or an object array as your format list.

For example, how do you prevent the following method call from throwing a FormatException exception?

result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                       nOpen, nClose)

A single opening or closing brace is always interpreted as the beginning or end of a format item. To be interpreted literally, it must be escaped. You escape a brace by adding another brace ("{{" and "}}" instead of "{" and "}"), as in the following method call:

result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                       nOpen, nClose)

However, even escaped braces are easily misinterpreted. We recommend that you include braces in the format list and use format items to insert them in the result string, as the following example shows.

result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
                       nOpen, "{", nClose, "}")

The most common cause of the exception is that the index of a format item doesn't correspond to an object in the format list. Usually this indicates that you've misnumbered the indexes of format items or you've forgotten to include an object in the format list. Occasionally, the exception is the result of a typo; for example, a typical mistake is to mistype "[" (the left bracket) instead of "{" (the left brace).

For example, the following code throws a FormatException exception:

Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim numbers(3) As Integer 
      Dim total As Integer = 0
      For ctr = 0 To 2
         Dim number As Integer = rnd.Next(1001)
         numbers(ctr) = number
         total += number
      Next
      numbers(3) = total
      Console.WriteLine("{0} + {1} + {2} = {3}", numbers)   
   End Sub 
End Module

This is a problem of compiler overload resolution. Because the compiler cannot convert an array of integers to an object array, it treats the integer array as a single argument, so it calls the Format(String, Object) method. The exception is thrown because there are four format items but only a single item in the format list.

Because neither Visual Basic nor C# can convert an integer array to an object array, you have to perform the conversion yourself before calling the Format(String, Object()) method. The following example provides one implementation.

Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim numbers(3) As Integer 
      Dim total As Integer = 0
      For ctr = 0 To 2
         Dim number As Integer = rnd.Next(1001)
         numbers(ctr) = number
         total += number
      Next
      numbers(3) = total
      Dim values(numbers.Length - 1) As Object
      numbers.CopyTo(values, 0) 
      Console.WriteLine("{0} + {1} + {2} = {3}", values)   
   End Sub 
End Module
Show:
© 2014 Microsoft