PowerShell: How to Round Numbers Up or Down


Often you may want to round numbers up or down to a specific number of decimal places in PowerShell.

You can use the [math]::ceiling and [math]::floor commands to do so.

The following examples show how to use these commands in practice.

Example 1: Round Number Up to Nearest Integer

We can use the following syntax to define an array of numbers and then round each number up to the nearest integer:

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

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

PowerShell round up to nearest integer

Notice that each value in the array has been rounded up to the nearest integer.

Example 2: Round Number Up to Specific Number of Decimal Places

We can use the following syntax to define an array of numbers and then round each number up to two decimal places:

$some_values = @(12.3488, 10.1, 20.0092, 15.972)
$some_values | ForEach-Object { [math]::ceiling($_*100) / 100 }

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

PowerShell round up to specific number of decimal places

Notice that each value in the array has been rounded up to a max of two decimal places.

Note: We multiplied each value by 100, then applied the ceiling command, then divided by 100 to round each value up to exactly 2 decimal places.

Example 3: Round Number Down to Nearest Integer

We can use the following syntax to define an array of numbers and then round each number down to the nearest integer:

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

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

PowerShell round down to integer

Notice that each value in the array has been rounded down to the nearest integer.

Example 4: Round Number Down to Specific Number of Decimal Places

We can use the following syntax to define an array of numbers and then round each number down to two decimal places:

$some_values = @(12.3488, 10.1, 20.0092, 15.972)
$some_values | ForEach-Object { [math]::floor($_*100) / 100 }

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

PowerShell round down to specific number of decimal places

Notice that each value in the array has been rounded down to a max of two decimal places.

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