PowerShell: How to Round Numbers to 2 Decimal Places


Often you may want to round numbers to 2 decimal places in PowerShell.

You can use the following methods to do so:

Method 1: Round Numbers to Exactly 2 Decimal Places

$some_values | ForEach-Object { '{0:N2}' -f $_ }

This particular example will round each number in the array named $some_values to exactly 2 decimal places.

Method 2: Round Numbers to a Max of 2 Decimal Places

$some_values | ForEach-Object { [math]::round($_, 2) }

This particular example will round each number in the array named $some_values to a max of 2 decimal places.

The following examples show how to use each method in practice.

Example 1: Round Numbers to Exactly 2 Decimal Places in PowerShell

We can use the following syntax to create an array named $some_values and round each value in the array to exactly 2 decimal places:

$some_values = @(12.3488, 10.1, 20.0092, 15.502)
$some_values | ForEach-Object { '{0:N2}' -f $_ }

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

PowerShell round to exactly 2 decimal places

Notice that each value in the output is rounded to exactly 2 decimal places.

By using the -f format operator with the syntax {0:N2} we specified that each value should have exactly 2 values after the decimal place.

Example 2: Round Numbers to Max of 2 Decimal Places in PowerShell

We can use the following syntax to create an array named $some_values and round each value in the array to a max of 2 decimal places:

$some_values = @(12.3488, 10.1, 20.0092, 15.502)
$some_values | ForEach-Object { [math]::round($_, 2) }

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

PowerShell round to max of 2 decimal places

Notice that each value in the output is rounded to a max of 2 decimal places.

For example, the value 10.1 rounded to 2 decimal places would be 10.10, but the round method only displays the necessary amount of decimal places up to a specific number.

Related Tutorials

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

PowerShell: How to Calculate the Average of an Array
PowerShell: How to Calculate Sum of Values in Array
PowerShell: How to Find Minimum and Maximum Values in Array
PowerShell: How to Find Duplicate Values in Array

Leave a Reply