Show Menu
Cheatography

String.Format syntax & format codes Cheat Sheet (DRAFT) by

Composite Formatting and Numeric Formats

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Composite Format Item Syntax

{index­[,a­lig­nme­nt]­[:f­orm­atS­tring]}

Explan­ation

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corres­ponding item in the list of objects
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-­aligned if alignment is positive and left-a­ligned if alignment is negative. If padding is necessary, white space is used
The optional format­String component is a format string that is approp­riate for the type of object being formatted

index Example 1

String.Fo­rma­t("Prime numbers less than 10: {0}, {1}, {2}, {3}", 2, 3, 5, 7)
Prime numbers less than 10: 2, 3, 5, 7

index Example 2

String.Fo­rma­t("0­x{0:X} {0:E} {0:N}", Int64.M­ax­Value)
0x7FFF­FFF­FFF­FFFFFF 9.2233­72E+018 9,223,­372­,03­6,8­54,­775­,807.00

alignment Example

Dim names() As String = {"Ad­am", "­Bri­dge­tte­", "­Car­la", "­Dan­iel­", "­Ebe­nez­er", "­Fra­nci­ne", "George"}
Dim hours() As Decimal = {40, 6.667D, 40.39D, 82, 40.333D, 80, 16.75D}
Console.WriteLine(String.Format("{0,-20} {1,5}", "­Nam­e", "Hours"))
Console.WriteLine()
For index As Integer = 0 To names.GetUpperBound(0)
   Console.WriteLine(String.Format("{0,-20} {1,5}", names(­index), hours(index)))
Next
Name                 Hours

Adam                    40
Bridgette            6.667
Carla                40.39
Daniel                  82
Ebenezer             40.333
Francine                80
George               16.75

format­String Example

String.Fo­rma­t("Name = {0}, hours = {1:hh}, minutes = {1:mm}­", "­Fre­d", DateTi­me.Now)
Name = Fred, hours = 11, minutes = 30

Sources