Thursday, August 30, 2007

Formatting through the -f parameter

Formatting in PowerShell is typically achieved through the use of .NET's format strings. You might have seen cryptic statements like:

"{0,-8:P1}" -f 1.75

The above format can be explained as:

"{argument index[,alignment][:formatString zeros]}"

Note that both the alignment and the formatString are optional.

argument index is used when formatting more than one argument.

##### Argument Index
"{0,8}{1,10}" -f "John", "Doe"        # " John Doe"
"{0,8}{1,10}" -f "Albert", "Smith"    # " Albert Smith"

alignment indicates the minimal length of the string.
Positive valus are right justified and padded with spaces on the left if the string size is shorter than the value.

Negative values are left justified and padded with spaces on the right if the string size is shorter than the value.

##### Alignment

"{0,10}" -f "orange"     # " orange"
"{0,-10}" -f "orange"    # "orange "

format string is used mainly for numeric formatting.

##### C - Currency, the number represents the number of trailing zeroes
"{0:C3}" -f 25        # "$25.000"
"{0:C3}" -f -25        # "($25.000)"

##### D - Decimal, the number represents the number of leading zeroes
"{0:D5}" -f 25        # "00025"
"{0:D5}" -f -25        # "-00025"

##### E - Exponential, the number represents the number of trailing zeroes
"{0:E5}" -f 25        # "2.50000E+E001"
"{0:E5}" -f -25        # "-2.50000E+E001"

##### N - Number, the number represents the number of trailing zeroes
"{0:N5}" -f 25        # "25.00000"
"{0:N5}" -f -25        # "-25.00000"

##### P - Percentage, the number represents the number of leading zeroes
"{0:P3}" -f 25        # "2,500.000%"
"{0:P3}" -f -25        # "-2,500.000%"

##### X - Hexadecimal, the number represents the number of leading zeroes
"{0:X5}" -f 25        # "00019"
"{0:X5}" -f -25        # "FFFFFFE7"


Here are a few examples. Try them yourself.

"{0,9:P2}{1,20}" -f 0.09,"Standard loan"
"{0,9:P2}{1,20}" -f 0.25,"High interest loan"
"{0,9:P2}{1,20}" -f 3.5,"Mafia loan"

"{0,10:N3}{1,10:N3}{2,10:N3}{3,10:N3}" -f 0.2, 0.3, 0.45, 0.91
"{0,10:N3}{1,10:N3}{2,10:N3}{3,10:N3}" -f 1.1, 3, 2.5, 91.1
"{0,10:N3}{1,10:N3}{2,10:N3}{3,10:N3}" -f 25, 300, 211.5, 450

1 comment:

Anonymous said...

Good words.