Format Strings

Server controls display numbers, text strings, and dates and times that can be formatted in various ways using an assortment of formatting techniques. These formats are applied through scripting to assign the value to a server control for display; certain formats are applied as part of the server control's embedded format string. These formatting methods are described below. Although there are multiple ways to produce a format, you will likely settle on only a few of the methods that best serve your purposes.

The String.Format() Method

One of the most useful and widely applicable formatting methods is String.Format(). This method is applied in script; its format string can also be declared for many server controls. Therefore, it is a general-purpose formatting method useful in about any coding situation. It can be used to format numbers, strings, and dates and times, returning a formatted value as a character string. The general format for this scripting this method is shown below.

String.Format("{index:format} [{index:format}]...", value [,value]...)
Figure 2-54. General format for the String.Format() method. method.

One or more {index:format} specifications, enclosed in quotes, are applied to one or more comma-separated data values, which follow the specifications. The index gives the particular value to which a format applies, numbered in sequence beginning with 0.

In the simplest configuration a single format is applied to a single value, with index 0 pointing to the first, and only, value.

String.Format("{0:format}", value)
Listing 2-60. Applying a simple format string.

In more elaborate form, multiple formats are applied to multiple values, with the index pointing to the order of values to which a format applies.

String.Format("{0:format} {1:format} {2:format}", value0, value1, value2)
Listing 2-61. Applying multiple format strings.

A formatted value can be embedded inside a surrounding text string by enclosing the text inside the format string.

String.Format("This is {0:format} surrounding text.", value)
Listing 2-62. Embedding a formatted value inside a text string.

Standard Numeric Format Strings

A number is formatted using a special format character that follows the index and is separated from it by a colon: "{index:format}". The following table describes the numeric format characters used to apply standard formatting to numbers.

Format Description
Cn|cn Currency. The number is converted to a string using the optional n (precision specifier) to indicate the number of decimal places to which to round and display. The number is preceded by a dollar sign with commas separating thousands positions. Negative values are enclosed in parentheses.
Dn|dn Decimal. The integer (only) number is converted to a string using the optional n (precision specifier) to indicate the number of decimal positions to which to round and display, padded with leading 0s if necessary. Negative values are preceded by a minus sign.
Fn|fn Fixed-point. The number is converted to a string using the optional n (precision specifier) to indicate the number of decimal positions to the right of the decimal point to which to round. Negative values are preceded by a minus sign. No comma separators are supplied.
Nn|nn Number. The number is converted to a string using the optional n (precision specifier) to indicate the number of decimal positions to the right of the decimal point to which to round. Negative values are preceded by a minus sign. Comma separators are supplied for the thousands positions.
Pn|pn Percent. The number is multiplied by 100 and converted to a string using the optional n (precision specifier) to indicate the number of decimal positions to the right of the decimal point to which to round. Negative values are preceded by a minus sign.
Figure 2-55. Standard numeric format strings.

Examples of applying the standard numeric format strings are shown in the following table.

Format Example Output
Cn|cn String.Format("{0:C}", 1234.56) $1,234.56
String.Format("{0:C3}", 1234.56789) $1,234.568
String.Format("{0:C}", -1234.5) ($1,234.50)
Dn|dn String.Format("{0:D}", 1234) 1234
String.Format("{0:D6}", 1234) 001234
String.Format("{0:D}", 11234) -1234
Fn|fn String.Format("{0:F}", 1234.56) 1234.56
String.Format("{0:F4}", 1234.56) 1234.5600
String.Format("{0:F1}", -1234.567) -1234.6
Nn|nn String.Format("{0:N}", 1234.56) 1,234.56
String.Format("{0:N4}", 1234.56) 1,234.5600
String.Format("{0:N1}", -1234.567) -1,234.6
Pn|pn String.Format("{0:P}", .1234) 12.34 %
String.Format("{0:P0}", .1234) 12 %
String.Format("{0:P1}", -.1234) -12.3 %
Figure 2-56. Examples of standard numeric format strings.

Custom Numeric Format Strings

Rather than using the standard format strings, you can create your own custom format strings. These custom strings appear inside the braces as models for output formatting, substituting for the standard strings. The following table shows the characters you can use to compose your own format strings.

Format Description
# Digit placeholder. A digit appearing in the number at this position also appears in the output string at this position; otherwise, no digit appears. A single # represents as many significant digits as appear in the number. Leading 0s are never displayed at the position. Negative numbers are displayed with a minus sign.
0 Zero placeholder. A digit appearing in the number at this position also appears in the output string at this position; otherwise a 0 appears. A single 0 represents as many significant digits as appear in the number. Additional 0 characters beyond the number of significant digits in the number represent 0 padding. Negative numbers are displayed with a minus sign.
. Decimal point. The location of the decimal point in the formatted number. # and 0 characters indicate the number of positions to the right of the decimal point. The # character position is filled with significant digits; the 0 characters pad with zeros. Numbers are rounded to the last indicated decimal position.
, Thousand separator. Indicates inclusion of commas as thousands separators in the output format. Must appear between two or more # or 0 digit indicators to the left of a decimal point.
% Percent placeholder. The number is multiplied by 100 prior to formatting. The % sign appears to the right of the displayed number.
Other Literal characters. All other characters appearing in the format string are represented as literal characters in the indicated position in the output string.
Figure 2-57. Custom numeric format strings.

Examples of applying the custom numeric format strings are shown in the following table.

Format Example Output
# String.Format("{0:#}", 12345) 12345
String.Format("{0:#}", -12345) -12345
String.Format("{0:#######}", 12345) 12345
0 String.Format("{0:0}", 12345) 12345
String.Format("{0:0}", -12345) -12345
String.Format("{0:0#####}", 12345) 012345
. String.Format("{0:#.##}", 123.45) 123.45
String.Format("{0:#.000}", 123.45) 123.450
String.Format("{0:#.##}", -123.456) -123.46
, String.Format("{0:#,#.##}", 1234.56) 1,234.56
String.Format("{0:#,#.#0}", 1234.5) 1,234.50
String.Format("{0:#,#.#0}", -1234.567) -1,234.57
% String.Format("{0:0.##%}", .1234) 12.34%
String.Format("{0:0.00%}", .12) 12.00%
String.Format("{0:0.00%}", .12345) 12.35%
Other String.Format("{0:$#,#.##}", 1234.56) $1,234.56
String.Format("{0:$ #,#.##}", 1234.56) $ 1,234.56
String.Format("{0:$#,###.##}", 1234.56) $1,234.56
String.Format("{0:[#,#.##]}", 1234.56) [1,234.56]
String.Format("{0:#0 Percent}", 12) 12 Percent
String.Format("You owe: {0:$#,#.##}", 1234.56) You owe: $1,234.56
Figure 2-58. Examples of custom numeric format strings.

Standard Date and Time Format Strings

A standard date/time format string consists of a single specifier character. Allowable characters are given in the following table.

Format Description
d Short date. Displays the short date format.
D Long date. Displays the long date format.
t Short time. Displays the short time format.
T Long time. Displays the long time format.
f Full date/short time. Displays the full date/time format with short time.
F Full date/long time. Displays the full date/time format with long time.
g General date/short time. Displays the full date/time format with short time.
G General date/long time. Displays the full date/time format with long time.
M|m Month/day. Displays the month name and day format.
Y|y Month/year. Displays the month name and year format.
s Sortable date/time. Displays the sortable date/time format.
Figure 2-59. Standard date/time format strings.

Examples of applying the standard date/time format strings are shown in the following table.

Format Example Output
d String.Format("{0:d}", Now) 2/5/2012
D String.Format("{0:D}", Now) Sunday, February 05, 2012
t String.Format("{0:t}", Now) 8:20 AM
T String.Format("{0:T}", Now) 8:20:47 AM
f String.Format("{0:f}", Now) Sunday, February 05, 2012 8:20 AM
F String.Format("{0:F}", Now) Sunday, February 05, 2012 8:20:47 AM
g String.Format("{0:g}", Now) 2/5/2012 8:20 AM
G String.Format("{0:G}", Now) 2/5/2012 8:20:47 AM
M String.Format("{0:M}", Now) February 05
Y String.Format("{0:Y}", Now) February, 2012
s String.Format("{0:s}", Now) 2012-02-05T08:20:47
Figure 2-60. Examples of standard date/time format strings.

Custom Date and Time Format Strings

In addition to the standard date/time format strings you can create your own custom strings. These strings appear inside the braces as models for output formatting, substituting for the standard strings. The following table shows the characters you can use to compose your own date/time strings.

Format Description
d Displays the day of the month as a single or double digit. (If this character appears without additional formatting it is interpreted as the standard short date format.)
dd Displays the day of the month with a leading 0 for single-digit months.
dddd Displays the full name of the day.
M Displays the numeric month as a single or double digit. (If this character appears without additional formatting it is interpreted as the standard month/day format.)
MM Displays the numeric month with a leading 0 for single-digit months.
MMM Displays the abbreviated name of the month.
MMMM Displays the full name of the month.
y Displays the year as a one- or two-digit number with the century digits omitted. (If this character appears without additional formatting it is interpreted as the standard month/year format.)
yy Displays the year as a two-digit number with a leading 0 for single-digit years, with the century digits omitted.
yyyy Displays the year as a four-digit number.
H|h Displays the hour as a one- or two-digit number. (Cannot appear stand-alone; must appear with other time format characters.)
m Displays the minute as a one- or two-digit number. (If it appears stand-alone it is interpreted as the standard month/day format.)
mm Displays the minute as a two-digit number with a leading 0 for single-digit minutes.
s Displays the seconds as a one- or two-digit number. (If it appears stand-alone it is interpreted as the standard sortable date/time format.)
ss Displays the seconds as a two-digit number with a leading 0 for single-digit seconds.
f... Displays fractions of seconds using up to 7 characters to display fractional digits.
/ - , Date separators.
: Time separator.
Other All other characters in the date/time format string are written to the output string as literal characters.
Figure 2-61. Custom date/time format strings.

Examples of applying custom date/time format strings are shown in the following table.

Format Example Output
d String.Format("{0:d}", Now) 2/5/2012
dd String.Format("{0:dd}", Now) 05
dddd String.Format("{0:dddd}", Now) Sunday
M String.Format("{0:M}", Now) February 05
MM String.Format("{0:MM}", Now) 02
MMM String.Format("{0:MMM}", Now) Feb
String.Format("{0:MMM dd}", Now) Feb 05
String.Format("{0:dd MMM}", Now) 05 Feb
MMMM String.Format("{0:MMMM}", Now) February
String.Format("{0:MMMM dd}", Now) February 05
String.Format("{0:dd MMMM}", Now) 05 February
y String.Format("{0:y}", Now) February, 2012
String.Format("{0:M d y}", Now) 2 5 12
yy String.Format("{0:yy}", Now) 12
String.Format("{0:M d yy}", Now) 2 5 12
yyyy String.Format("{0:yyyy}", Now) 2012
String.Format("{0:d MMMM yyyy}", Now) 5 February 2012
/ - , String.Format("{0:dd/MM/yyyy}", Now) 05/02/2012
String.Format("{0:dd-MMMM-yyyy}", Now) 05-February-2012
String.Format("{0:MMMM d, yyyy}", Now) February 5, 2012
H String.Format("{0:HH}", Now) 08
mm String.Format("{0:mm}", Now) 20
String.Format("{0:H:mm}", Now) 8:20
ss String.Format("{0:ss}", Now) 47
String.Format("{0:H:m:ss}", Now) 8:20:47
f... String.Format("{0:H:mm:ssffff}", Now) 8:20:4717855
Other String.Format("Today is {0:MMM d, yyyy}", Now) Today is Feb 5, 2012
String.Format("The time is {0:H:mm:ss}", Now) The time is 8:20:47
Figure 2-62. Examples of custom date/time format strings.

Formatting Text Strings

String values are formatted by supplying only an index. That is, there is no special formatting that takes place. The String.Format() method simply repeats the value of the string, possibly surrounding it with fixed text or with XHTML tags to apply styling.

Format Example Output
{0} String.Format("{0}", "This is a string") This is a string
String.Format("{0} {1}", "This is", "a string") This is a string
String.Format("{0} <b>{1}</b>", "This is", "a string") This is a string
Figure 2-63. Examples of formatting strings.

All of the above examples show formatting applied in script using the String.Format() method. Certain server controls also recognize these same format strings. For instance, some controls have a DataTextFormatString property to supply formatting for a data value displayed by the control. The above format strings are applied in this property.

<asp:control Runat="Server">
  DataTextFormatString="{0:$#,#.##}"
  .../>
Listing 2-63. Setting a control's data format string.

When these formatting occasions arise, you will be reminded to check back to this page for help in formatting server control information.

Visual Basic Formats

The VB.NET language provides numerous ways to format strings, numbers, and dates in addition to those provided in the String.Format() method. These formats, though, pertain only to scripting methods. They cannot be applied directly to server control formatting properties. Still, they offer convenience and flexibility that match format string methods.

Formatting Currency

The Visual Basic FormatCurrency() function formats numeric data for presentation as dollars and cents. Its general format is shown below.

FormatCurrency(value [, trailing] [, leading] [, parentheses] [, group])
Figure 2-64. General format for FormatCurrency() function.

In the above format,

value is any expression that produces a number;

trailing (digits) is an optional integer giving the number of digits following the decimal point; the default is rounding to 2 digits;

leading (digit) is True (default) or False to indicate whether a leading 0 is to appear before the decimal point for fractional values;

parentheses is True (default) or False to indicate whether negative numbers should be displayed inside parentheses;

group (digits) is True (default) or False to indicate whether numbers should be grouped between commas.

Format Output
FormatCurrency(12345.6789) $12,345.68
FormatCurrency(12345.6789, 4) $12,345.6789
FormatCurrency(12345.6789,,,,False) $12345.68
FormatCurrency(-12345.6789) ($12,345.68)
FormatCurrency(-12345.6789,,,False) -$12,345.68
FormatCurrency(.6789) $0.68
FormatCurrency(.6789,,False) $.68
FormatCurrency(-.6789,,False,False) -$.68
Figure 2-65. Example uses of FormatCurrency() function.

Formatting Numbers

The FormatNumber() function returns a value formatted as a number. Its general format is shown below.

FormatNumber(value [, trailing] [, leading] [, parentheses] [, group])
Figure 2-66. General format for FormatNumber() function.

In the above format,

value is any expression that produces a number;

trailing (digits) is an optional integer giving the number of digits following the decimal point; the default is rounding to 2 digits;

leading (digit) is True (default) or False to indicate whether a leading 0 is to appear before the decimal point for fractional values;

parentheses is True or False (default) to indicate whether negative numbers should be displayed inside parentheses;

group (digits) is True (default) or False to indicate whether numbers should be grouped between commas.

Format Output
FormatNumber(12345.6789) 12,345.68
FormatNumber(12345.6789,5) 12,345.67890
FormatNumber(12345.6789,,,,False) 12345.68
FormatNumber(-12345.6789) -12,345.68
FormatNumber(-12345.6789,,,True) (12,345.68)
FormatNumber(.6789) 0.68
FormatNumber(.6789,,False) .68
FormatNumber(-.6789,4) -0.6789
Figure 2-67. Example uses of FormatNumber() function.

Formatting Percentages

The FormatPercent() function returns a value formatted as a percentage, that is, multiplied by 100 with a trailing % character. Its general format is shown below.

FormatPercent(value [, trailing] [, leading] [, parentheses] [, group])
Figure 2-68. General format for FormatPercent() function.

In the above format,

value is any expression that produces a number;

trailing (digits) is an optional integer giving the number of digits following the decimal point; the default is rounding to 2 digits;

leading (digit) is True (default) or False to indicate whether a leading 0 is to appear before the decimal point for fractional values;

parentheses is True or False (default) to indicate whether negative numbers should be displayed inside parentheses;

group (digits) is True (default) or False to indicate whether numbers should be grouped between commas.

Format Output
FormatPercent(.6789) 67.89%
FormatPercent(.6789,4) 67.8900%
FormatPercent(-.6789) -67.89%
FormatPercent(-.6789,,,True) (67.89%)
Figure 2-69. Example uses of FormatPercent() function.

Formatting Dates and Times

The FormatDateTime() function returns a string expression representing a date/time value. Its general format is shown below.

FormatDateTime(value [, DateFormat.format])
Figure 2-70. General format for FormatDateTime() function.

In the above format, value is a date or time value and format is one of the following values: GeneralDate (default), LongDate, ShortDate, LongTime, or ShortTime.

Format Output
FormatDateTime(Now)2/5/2012 8:20:47 AM
FormatDateTime(Today)2/5/2012
FormatDateTime(TimeOfDay)8:20:47 AM
FormatDateTime(Now,DateFormat.LongDate)Sunday, February 05, 2012
FormatDateTime(Today,DateFormat.LongDate)Sunday, February 05, 2012
FormatDateTime(Now,DateFormat.ShortDate)2/5/2012
FormatDateTime(Today,DateFormat.ShortDate)2/5/2012
FormatDateTime(Now,DateFormat.LongTime)8:20:47 AM
FormatDateTime(TimeOfDay,DateFormat.LongTime)8:20:47 AM
FormatDateTime(Now,DateFormat.ShortTime)08:20
FormatDateTime(TimeOfDay,DateFormat.ShortTime)08:20
Figure 2-71. Example uses of FormatDateTime() function.

The Format() Function

The Format() function is a general-purpose formatting function that returns a string value formatted according to a format string. The format strings duplicate currency, numeric, and date/time formats produced by the specialized formats described above. The general format for applying the Format() function is shown below.

Format(value, "format string")
Figure 2-72. General format for Format() function.

Formatting Numbers

A format string for numeric values can use one of the predefined string values shown in the following table.

String Description
General Number|G|g Displays number with no thousand separator.
Currency|C|c Displays number with thousand separator, if appropriate; display two digits to the right of the decimal separator.
Fixed|F|f Displays at least one digit to the left and two digits to the right of the decimal separator.
Standard|N|n Displays number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent Displays number multiplied by 100 with a percent sign (%) appended immediately to the right; always displays two digits to the right of the decimal separator.
P|p Displays number with thousandths separator multiplied by 100 with a percent sign (%) appended to the right and separated by a single space; always displays two digits to the right of the decimal separator.
Figure 2-73. Format strings for numeric values using the Format() function.

Examples of applying a format string to numeric values are shown in the following table.

Format Output
Format(12345.6789,"g")12345.6789
Format(12345.6789,"c")$12,345.68
Format(12345.6789,"f")12345.68
Format(12345.6789,"n")12,345.68
Format(-12345.6789,"g")-12345.6789
Format(-12345.6789,"c")($12,345.68)
Format(-12345.6789,"f")-12345.68
Format(-12345.6789,"n")-12,345.68
Format(.6789,"Percent")67.89%
Format(.6789,"p")67.89 %
Format(-.6789,"Percent")-67.89%
Format(-.6789,"p")-67.89 %
Figure 2-74. Examples of formatting numeric values with the Format() function.

Formatting Dates and Times

A format string for date/time values can use one of the predefined string values shown in the following table.

String Description
Long Date|D Displays a date in long date format.
Short Date|d Displays a date in short date format.
Long Time|T Displays the time in long time format.
Short Time|t Displays the time in short time format.
F Displays the long date and long time.
f Displays the long date and short time.
g Displays the short date and short time.
M|m Displays the month and the day of a date.
Y|y Displays the month and the year.

Figure 2-75. Format strings for date/time values using the Format() function.

Examples of applying a format string to date/time values are shown in the following table.

Format Output
Format(Now,"D")Sunday, February 05, 2012
Format(Now,"d")2/5/2012
Format(Now,"T")8:20:47 AM
Format(Now,"t")8:20 AM
Format(Now,"F")Sunday, February 05, 2012 8:20:47 AM
Format(Now,"f")Sunday, February 05, 2012 8:20 AM
Format(Now,"g")2/5/2012 8:20 AM
Format(Now,"m")February 05
Format(Now,"y")February, 2012
Figure 2-76. Examples of formatting date/time values with the Format() function.

Custom Numeric Formats

Custom formats can be defined for displaying numeric values by composing a string to describe the format. This user-defined string is applied through the Format() function. The characters shown in the following table are used to compose the format string.

Character Description
0 Digit placeholder. Displays a digit or a zero. If the value has a digit in the position, then it displays; otherwise, a zero is displayed.
# Digit placeholder. Displays a digit or a space. If the value has a digit in the position, then it displays; otherwise, a space is displayed.
. Decimal placeholder; determines how many digits are displayed to the left and right of the decimal separator.
, Thousand separator; separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Only a single "," is required in the format, between the first set of digit placeholders.
% Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears in the format string.
- + $ ( ) Literal characters; displayed exactly as typed in the format string.
Figure 2-77. Custom characters for composing numeric format strings using the Format() function.

Examples of applying a user-defined format string to numeric values are shown in the following table.

Format Output
Format(012345.6789,"0.00")12345.68
Format(012345.6789,"0,0.000")12,345.679
Format(012345.6789,"00000,0.000000")012,345.678900
Format(012345.6789,"#.##")12345.68
Format(012345.6789,"#,#.##")12,345.68
Format(012345.6789,"$ #,#.##")$ 12,345.68
Format(-012345.6789,"#,#.####")-12,345.6789
Format(-012345.6789,"$#,#.##")-$12,345.68
Format(.6789,"#,#.##").68
Format(.6789,"0,0.000")00.679
Format(-.6789," 0.0000")- 0.6789
Format(.6789,"0.00%")67.89%
Figure 2-78. Examples of custom numeric format strings using the Format() function.

Custom Date/Time Formats

Custom formats can be defined for displaying date and time values by composing a string to describe the format. This user-defined string is applied through the Format() function. The characters shown in the following table are used to compose the date/time format string.

Character Description
: Time separator.
/ - Date separators.
% Precedes a single-character format string.
d Displays the day as a number without a leading zero.
dd Displays the day as a number with a leading zero.
ddd Displays the day name as an abbreviation.
dddd Displays the day as a full name.
M Displays the month as a number without a leading zero.
MM Displays the month as a number with a leading zero.
MMM Displays the month name as an abbreviation.
MMMM Displays the month as a full name.
yy Displays the year in two-digit format.
yyyy Displays the year in four-digit format.
h Displays the hour as a number without leading zeros using the 12-hour clock.
hh Displays the hour as a number with leading zeros using the 12-hour clock.
H Displays the hour as a number without leading zeros using the 24-hour clock.
HH Displays the hour as a number with leading zeros using the 24-hour clock.
m Displays the minute as a number without leading zeros.
mm Displays the minute as a number with leading zeros.
s Displays the seconds as a number without leading zeros.
ss Displays the seconds as a number with leading zeros.
f... Displays fractions of seconds using up to 7 characters to display fractional digits.
tt Uses the 12-hour clock and displays an uppercase AM with any hour before noon; displays an uppercase PM with any hour between noon and 11:59 P.M.
Other Additional characters and punctuation marks can be used within the format string. Characters that match any of the formatting characters must be preceded by "\".
Figure 2-79. Custom characters for composing date/time format strings using the Format() function.

Examples of applying custom format strings to date/time values are shown in the following table.

Format Output
Format(Now,"M/d/yy")2/5/12
Format(Now,"M-d-yyyy")2-5-2012
Format(Now,"d-MMMM-yy")5-February-12
Format(Now,"d MMMM, yyyy")5 February, 2012
Format(Now,"MMMM d, yyyy")February 5, 2012
Format(Now,"MMMM, yyyy")February, 2012
Format(Now,"%d")5
Format(Now,"h:m tt")8:20 AM
Format(Now,"h:m:ss tt")8:20:47 AM
Format(Now,"H:m")8:20
Format(Now,"M/d/yy - h:mtt")2/5/12 - 8:20AM
Format(Now,"H:m:ss.fffffff")8:20:47.1785598
Format(Now,"Today is MMMM d, yyyy.")Today is February 5, 2012.
Figure 2-80. Examples of custom date/time format strings using the Format() function.

There certainly are a lot of formats that can be applied. However, as mentioned above, you will not likely use all of the possible combinations. You will probably settle on a few standard formats that serve your needs, and ignore the rest, unless special situations dictate finding that one special format that you need.