Powershell Round up Function

Powershell Round up Function

I would like to round up to two decimal places in Powershell.

I start with the double "178.532033". If I use the Excel ROUNDUP function to two decimal places I get "178.54".

=ROUNDUP(A1,2)

However, if I use the Round function contained within the Math class in Powershell I get the result "178.53" (because I am rounding as opposed to rounding up):

$value = 178.532033

Write-Output = ([Math]::Round($value, 2))

Is there a way to round up to two decimal places in Powershell?

6

3 Answers

This is handled easily by the ceiling and floor methods of the math class.

Script:

$a = 657
$b = 234

$a/$b
[math]::floor($a/$b)
[math]::ceiling($a/$b)

Output:

2.80769230769231
2
3

If you want to round to two decimal places, multiply by 100 before using floor/ceiling then divide the result by 100.

I find that you are rarely going to be the last person to edit a PowerShell script, and keeping them simple is key to not getting an e-mail a year later wondering what you were doing with a complex transformation in a script that no longer works.

Just add 0.005 before rounding:

$value = 178.532033
Write-Output = ([Math]::Round($value + 0.005, 2))

This takes the interval [1.000, 1.010) to [1.005, 1.015). All the values in the first interval ROUNDUP(2) to 1.01, and all the values in the second interval ROUND(2) to 1.01.

In general, if rounding to k places after the decimal, add 0.5/10^k to round up, or subtract that to round down, by rounding the result normally.

1

Rounddown:

$a = 9;
$b = 5;
[math]::truncate($a/$b)

Roundup:

$a = 9;
$b = 5;
if ( ($a % $b) -eq 0 )
{
  $a/$b
}
else 
{
  [math]::truncate($a/$b)+1
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.