PowerShell: How to Format Numbers to 2 Decimal Places


You can use the following methods to format numbers to 2 decimal places in PowerShell:

Method 1: Round Number to 2 Decimal Places

[math]::round($my_number, 2)

This particular example rounds the number stored in the $my_number variable to 2 decimal places.

For example, if $my_number contains 1500.347 then this will return 1500.35.

Method 2: Truncate Number to 2 Decimal Places

[math]::truncate($my_number * 100) / 100

This particular example truncates the number stored in the $my_number variable to 2 decimal places.

For example, if $my_number contains 1500.347 then this will return 1500.34.

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

Example 1: Format Number to 2 Decimal Places in PowerShell

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

We can use the following syntax to round this number to 2 decimal places:

$my_number = 1500.347
[math]::round($my_number, 2)

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

PowerShell round number to 2 decimal places

Notice that the number is rounded to 1500.35.

It’s worth noting that this syntax will only round a number to 2 decimal places if there are at least 2 decimal places in the number.

For example, if our number was 1500.1 then this syntax would simply return 1500.1:

Example 2: Truncate Number to 2 Decimal Places in PowerShell

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

We can use the following syntax to truncate this number to 2 decimal places:

$my_number = 1500.347
[math]::truncate($my_number * 100) / 100

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

PowerShell truncate number to 2 decimal places

Notice that the number is simply truncated to two decimal places, resulting in 1500.34.

Related Tutorials

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

PowerShell: How to Format Numbers with Commas
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