Composite Formatting

("In-Line" Formatting)

 

Composite formatting takes a list of objects and a composite format string as input. A composite format string consists of fixed text intermixed with indexed placeholders, called format items, that correspond to the objects in the list. The formatting operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.

 

Composite formatting can be used with the String.Format method and the Console.WriteLine method.

 

A composite format string and object list are used as arguments of methods that support the composite formatting feature. A composite format string consists of zero or more runs of fixed text intermixed with one or more format items. The fixed text is any string that you choose, and each format item corresponds to an object (variable) in the list. The composite formatting feature returns a new result string where each format item is replaced by the string representation of the corresponding object in the list.

 

Composite formatting can be illustrated by the following code:

 

Dim strProduct As String = "jacket"

Dim decPrice As Decimal = 37.5

Dim strOutput As String = String.Format("The {0} sells for {1:c}.", strProduct, decPrice)

Console.WriteLine(strOutput)

 

The result would be:

The jacket sells for $37.50.

 

In the above example, the composite format string is "The {0} sells for {1:c}.". The fixed text is "The" and " sells for ", and the format items are "{0}", which corresponds to the variable strProduct, and "{1:c}", which corresponds to the variable decPrice.

 

Format Item Syntax

 

The format item takes the following form: {index[,alignment][:formatString]}

 

The enclosing braces ("{" and "}") are required, as is index.

 

Index refers to an item in the list: an index of 0 refers to the first item; 1 refers to the second item, 2 to the third, and so on.

 

The indexes are usually in order, but need not be. For example, the code:

Dim strStooge1 As String = "Moe"

Dim strStooge2 As String = "Larry"

strStooge3 As String = "Curly"

Console.WriteLine("The Three Stooges are {2}, {0}, and {1}.", strStooge1, strStooge2, strStooge3)

would produce this output:

The Three Stooges are Curly, Moe, and Larry.

 

The same index can appear multiple times in the format string to refer to the same item in the list as many times as necessary. For example, the code:

Console.WriteLine("Today is {0:dddd}, {0:MMMM} {0:dd}.", Date.Today)

would produce this output (given that the code was run on January 17, 2012):

Today is Tuesday, January 17.

 

Alignment is an optional component of the format item that enables you to specify padding and justification for a list item. If used, it is specified as a signed integer following the index and preceded by a comma. If the alignment value is positive, the data is right-justified and padded on the left with spaces within the width specified. If the alignment value is negative, the data is left-justified and padded on the right with spaces within the width specified.

The code:

Console.WriteLine("--{1,10}--", "test")

would produce this output:

--      test--

The code:

Console.WriteLine("--{1,-10}--", "test")

would produce this output:

--test      --

 

FormatString is an optional component of the format item that enables you to specify a standard (pre-defined) format or a custom format to be applied to the corresponding list item. The list item should be a number or a date, and the format string should be appropriate for the type of item being formatted.

 

 

Formatting Numbers

 

The following pre-defined specifiers can be used to format a numeric value:

 

specifier

type

format

output
(double 1.2345)

output
(int -12345)

c

currency

{0:c}

$1.23

($12,345.00)

d

decimal
(whole number)

{0:d}

Error. Convert to integer first; result will be 1.

-12345

e

exponent / scientific

{0:e}

1.234500e+000

-1.234500e+004

f

fixed point

{0:f}

1.23

-12345.00

g

general

{0:g}

1.2345

-12345

n

number

{0:n}

1.23

-12,345.00

r

round trippable

{0:r}

1.2345

-12345

x

hexadecimal

{0:x4}

Error. Convert to integer first; result will be 0001.

ffffcfc7

 

 

The following characters can be used to create a custom specifier for formatting a numeric value:

 

specifier

type

format

output
(double 1.2345)

0

zero placeholder

{0:00.000}

1234.560

#

digit placeholder

{0:#.##}

1234.56

.

decimal point placeholder

{0:0.0}

1234.6

,

thousand separator

{0:0,0}

1,235

%

percentage

{0:0%}

123456%

 

To demonstrate composite formatting for numbers with the pre-defined and custom specifiers described above, create a new "Try It" project, and place the following code in Sub Main:

 

        Dim strUserInput As String

        Dim dblTestNumber As Double

        Console.Write("Please enter a number to demonstrate named numeric formats: ")

        strUserInput = Console.ReadLine()

        dblTestNumber = Val(strUserInput)

        Console.WriteLine()

        Console.WriteLine("Output using named format specifiers:")

        Console.WriteLine("-------------------------------------")

        Console.WriteLine("Using c:  {0:c}", dblTestNumber)

        Console.WriteLine("Using d:  {0:d}", Convert.ToInt32(dblTestNumber))

        Console.WriteLine("Using e:  {0:e}", dblTestNumber)

        Console.WriteLine("Using f:  {0:f}", dblTestNumber)

        Console.WriteLine("Using g:  {0:g}", dblTestNumber)

        Console.WriteLine("Using n:  {0:n}", dblTestNumber)

        Console.WriteLine("Using r:  {0:r}", dblTestNumber)

        Console.WriteLine("Using x4: {0:x4}", Convert.ToInt32(dblTestNumber))

        Console.WriteLine()

        Console.WriteLine("Output using custom number formatting:")

        Console.WriteLine("--------------------------------------")

        Console.WriteLine("Zero placeholder:          {0,10:00.000}", dblTestNumber)

        Console.WriteLine("Digit placeholder:         {0,10:#.##}", dblTestNumber)

        Console.WriteLine("Decimal point placeholder: {0,10:0.0}", dblTestNumber)

        Console.WriteLine("Thousand separator:        {0,10:0,0}", dblTestNumber)

        Console.WriteLine("Percentage:                {0,10:0%}", dblTestNumber)

        Console.ReadLine()

 

 

Run the project and enter 1234.56. The output will be displayed as shown in the screen shot on the right.

 

Test the code using a variety of different values, including negative numbers and zero.

 

 

Download the VB.NET project code for the example above here.

 

 

Formatting Dates

 

The following pre-defined specifiers can be used to format dates:

 

specifier

type

output
(for January 17, 2012 at 11:19:21 AM)

d

Short Date

1/17/2012

D

Long Date

Tuesday, January 17, 2012

t

Short Time

11:19 AM

T

Long Time

11:19:21 AM

f

Full date and time

Tuesday, January 17, 2012 11:19 AM

F

Full date and time (long)

Tuesday, January 17, 2012 11:19:21 AM

g

Default date and time

1/17/2012 11:19 AM

G

Default date and time (long)

1/17/2012 11:19:21 AM

M

Day / Month

January 17

r

RFC1123 date string

Tue, 17 Jan 2012 11:19:21 GMT

s

Sortable date/time

2012-01-17T11:19:21

u

Universal time, local timezone

2012-01-17 11:19:21Z

Y

Month / Year

January, 2012

 

The following characters can be used to create a custom specifier for formatting a date value:

 

specifier

type

output
(for January 17, 2012 at 11:19:21 AM)

dd

Day

17

ddd

Short Day Name

Tue

dddd

Full Day Name

Tuesday

hh

2 digit hour

11

HH

2 digit hour (24 hour)

11

mm

2 digit minute

19

MM

Month

01

MMM

Short Month name

Jan

MMMM

Month name

January

ss

seconds

21

tt

AM/PM

AM

yy

2 digit year

12

yyyy

4 digit year

2012

:

seperator, e.g. {0:hh:mm:ss}

11:19:21

/

seperator, e.g. {0:MM/dd/yyyy}

01/17/2012

 

To demonstrate composite formatting for dates with the pre-defined and custom specifiers described above, create a new "Try It" project, and place the following code in Sub Main:

 

        Console.WriteLine("Date Formatting with Pre-defined Specifiers:")

        Console.WriteLine("--------------------------------------------")

        Console.WriteLine("Using d: {0:d}", Now)

        Console.WriteLine("Using D: {0:D}", Now)

        Console.WriteLine("Using t: {0:t}", Now)

        Console.WriteLine("Using T: {0:T}", Now)

        Console.WriteLine("Using f: {0:f}", Now)

        Console.WriteLine("Using F: {0:F}", Now)

        Console.WriteLine("Using g: {0:g}", Now)

        Console.WriteLine("Using G: {0:G}", Now)

        Console.WriteLine("Using M: {0:M}", Now)

        Console.WriteLine("Using r: {0:r}", Now)

        Console.WriteLine("Using s: {0:s}", Now)

        Console.WriteLine("Using u: {0:u}", Now)

        Console.WriteLine("Using Y: {0:Y}", Now)

        Console.WriteLine()

        Console.WriteLine("Date Formatting with Custom Specifiers:")

        Console.WriteLine("--------------------------------------------")

        Console.WriteLine("Today is: {0:dddd}, {0:MMMM} {0:dd}, {0:yyyy}", Now)

        Console.WriteLine("Today is: {0:ddd}, {0:MMM} {0:dd}, {0:yy}", Now)

        Console.WriteLine("Today is: {0:MM/dd/yyyy}", Now)

        Console.WriteLine("The current time is: {0:hh:mm:ss tt}", Now)

        Console.WriteLine("The current time is: {0:HH:mm:ss}", Now)

        Console.ReadLine()

 

Run the project to see the current date and time formatted in a variety of ways:

 

 

Download the VB.NET project code for the example above here.