Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 498
JHarley1 Avatar asked Dec 11 '22 05:12

JHarley1


1 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.

like image 149
Graham Avatar answered Dec 18 '22 18:12

Graham