Number formatting with the Format-Operator -f on PowerShell 7

Beneath DateTime formatting, number formatting is also a very important matter in dealing with data in PowerShell. Even if PowerShell already comes with support for data units (MB, GB, TB, …) there are a lot of other data formats which need to be handled like monetary values.

As PowerShell 7 is about to be released next year, i thought its time to prove that formatting is working on the preview (6 in this case) and create a useful article as a reference.

First, lets store some example values in variables.

123.456,00 €
Transform a int value to a currency „c“.

1,234560e+005
The scientific, exponential „e“ format.

Standard number formatting

123456,000
If you may want to present the value with fixed decimals, use „f“.

9876,54
For a general format with a comma as the separator use „g“.

123.456,000
The „n“ option displays a typical number format.

0,988 %
If you need to deal with percentage values, use the „p“ in your format string.

1e240
Hexadecimal presentation is done with „x“.

So far for the standard number formatters. If you need more specific formatting there are custom formatting options as well.

Custom number formatting

0000123456
Leading zeros can be done with adding „0“´s like below.

9876.54 ==> 9877
Rounding to the next full int can also be done with „#“.

$123.456,00
A custom currency format can be achieved with the characters # and 0 as shown below.

(123) 456 – 7890
For larger numbers you may use a easy to read complete customized version like this.

The value is
123456

You may even use escape characters, like the line break `n to produce multi-line output.

1234 – 5 @ 67 & 8 ( 9 $ 0 % 0 & 0 §
Maybe useless, but unlimited complexity is possible with custom formatting.

0.009876 ==> 0,99%
Custom formatting also allows you to round i.e. percentages.

Value-dependent formatting

Like in Microsoft Excel, you are able to format number, dependent if they are positive, negative of NULL. This works, by using the ‚;‘ separator in the formatting string with three sections:

format for positive valuesformat for negative valuesformat fir null values

Lets use an example for money and lets create some sample data first.

So we have three values here. If the value is positive, we want to show it as currency, because positive values will use the first part of the format string which is €#,##0.00 in our case.
€ 100,00

For negative values we want to show them in round-brackets (same format string as above, but this time the second part is used: (€#,##0.00)
(€ 200,00)

And now finally, if it is zero „0“ we want to show the string „Zero“ and the format operator uses the third part of the string.

So i hope you find this useful. If you want to know more, go to further output examples on MSDN, or the source docs page i used for this article here.

Cheers / Roman