How to Format Numbers with Commas in PowerShell


You can use the following syntax to format a number with commas in PowerShell:

$my_number.ToString("N0")

This particular example formats the number stored in the $my_number variable with commas and specifies that no decimal points should be shown.

To specify the number of decimal points, simply change the 0 to a different number.

For example, you could use the following syntax to specify that the number should be shown with commas and exactly 2 decimal points:

$my_number.ToString("N2")

The following example shows how to use this syntax in practice.

Example: How to Format Numbers with Commas in PowerShell

Suppose that we create a variable in PowerShell named $my_number that contains the number 346000.

We can use the following syntax to display this number with commas and no decimal places:

$my_number = 3460000
$my_number.ToString("N0")

The following screenshot shows how to use this syntax in practice:

PowerShell format number with commas

Notice that the number is formatted as 3,460,000.

If we’d like, we can use the following syntax to format the number with two decimal places:

$my_number = 3460000
$my_number.ToString("N2")

The following screenshot shows how to use this syntax in practice:

PowerShell format number with commas and specific number of decimal places

Notice that the number is formatted as 3,460,000.00.

Note: If the number has more than two decimal places and you specify a format of N2, then the number will be rounded to two decimal places.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Format-Table and Control Column Width
PowerShell: How to Use Format-Table with No Header
PowerShell: How to Format a DateTime

Leave a Reply