JHarley1
JHarley1

Reputation: 2112

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?

Upvotes: 15

Views: 63738

Answers (4)

woter324
woter324

Reputation: 3080

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

Upvotes: 1

Graham
Graham

Reputation: 7802

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.

Upvotes: 24

lijun1234
lijun1234

Reputation: 21

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
}

Upvotes: 1

Patrick87
Patrick87

Reputation: 28302

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.

Upvotes: 7

Related Questions