PowerShell: Format String
💡 TIP: Operator names are case-insensitive.
String Format Operator: -f
the string format operator syntax:
string -f args
use
{0}
{1}
{2}
etc
as placeholder in string.
(Microsoft calls this composite formatting)
"a {0} b {1}" -f 3, 4 # a 3 b 4 "a {1} b {0}" -f 3, 4 # a 4 b 3
Syntax for Placeholder
one of:
{index}
{index:formatString}
if you need alignment, use one of:
{index,alignment}
{index,alignment:formatString}
value meaning
- index is a integer, starting from 0.
- alignment is a integer. Means width. Positive means align right. Negative means align left.
- formatString is a short string indicating how to format it (e.g. Binary, hexadecimal, number of decimal places, with 3-digits grouping separator, etc.).
Format Code for Numbers
here are the code for the output format.
The codes are Case-Insensitive
d
→ decimale
→ scientific notationf
→ fixed-pointg
→ general (either fixed-point format or scientific, whichever is shorter.)
b
→ binaryx
→ hexadecimal
c
→ currencyn
→ number with group separatorsp
→ percentr
→ roundtrip (a string representation of the exact number)
Escaping Braces
to include literal braces, use double braces.
"{{literal braces}} {0}" -f 3 # {literal braces} 3
Example: Output Decimal Numbers
# show 2 decimal places "{0:f2}" -f 12.345 # 12.35 # show 5 decimal places "{0:f5}" -f 12.345 # 12.34500 # show 2 decimal places, with grouping "{0:n2}" -f 123456789.123456789 # 123,456,789.12
Example: Output Integer
# show zero decimal places "{0:f0}" -f 12.345 # 12 # show zero decimal places, with grouping "{0:n0}" -f 1234567.1234567 # 1,234,567
Example: Output Hexadecimal
(input should be integer only)
"{0:f0} in hexadecimal is {0:x}" -f 10 # 10 in hexadecimal is a
Example: Output Binary
(input should be integer only)
"{0:f0} in binary is {0:b}" -f 10 # 10 in binary is 1010
Example: Output Currency
# by default, 2 decimal places "{0:c}" -f 12.3456 # $12.35 # output 4 decimal places "{0:c4}" -f 12.34 # $12.3400
Example: Pad 0 in Front
# pad with three 0 in front "this number {0:000}" -f 3 # this number 003 "this number {0:000}" -f 1234 # this number 1234
Example: Pad Space in Front
# pad space, total width 4 "pad space {0,4}" -f 123
PowerShell String
- PowerShell: Quote String
- PowerShell: Double Quoted String, String Expansion
- PowerShell: Here-String
- PowerShell: Escape Characters
- PowerShell: String Operators
- PowerShell: Join String
- PowerShell: Split String
- PowerShell: Format String
- PowerShell: String Methods
- PowerShell: String Wildcards
- PowerShell: Regular Expression Operators
- PowerShell: Regular Expression Syntax