7

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
    Are you looking for this? See the detailed explanation by mklement0. Sep 3, 2018 at 11:07
  • 3
    [Math]::Round([Math]::Ceiling($value * 100) / 100, 2) Sep 3, 2018 at 11:29
  • [Math]::Ceiling($value * 100) / 100; Sep 3, 2018 at 11:38
  • @KirillPashkov The division returns a double value. See here for why rounding that result is not optional. Sep 3, 2018 at 13:53
  • A rational round up function would give 178.53 if I understand it correctly. You'd get 178.54 if the thousandths value was 5-9.
    – duffymo
    Sep 4, 2018 at 15:00

4 Answers 4

16

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.

4

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.

2
  • Simple, effective, beautiful. Great answer.
    – Arbiter
    Mar 2, 2021 at 20:58
  • Goes the wrong way for negative values
    – Walter A
    Mar 20 at 14:27
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
}
0

I want the returned value padded with zeros.

Given the value 10.99822

[Math]::Ceiling(10.99822 * 100)/100

Returns: 11

To add zero padding:

"{0:n2}" -f ([Math]::Ceiling(10.99822 * 100)/100)

Returns: 11.00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.