Question:
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”.
1 2 |
=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):
1 2 3 4 |
$value = 178.532033 Write-Output = ([Math]::Round($value, 2)) |
Is there a way to round up to two decimal places in Powershell?
Answer:
This is handled easily by the ceiling
and floor
methods of the math class.
Script:
1 2 3 4 5 6 7 |
$a = 657 $b = 234 $a/$b [math]::floor($a/$b) [math]::ceiling($a/$b) |
Output:
1 2 3 4 |
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.