PowerShell: Format String

By Xah Lee. Date: . Last updated: .

💡 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:

if you need alignment, use one of:

value meaning

Format Code for Numbers

here are the code for the output format.

The codes are Case-Insensitive

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