Thursday, July 9, 2015

Rounding Numbers

If you want to round numbers in PowerShell, then you have two choices (at least) with slightly different results.

Let's set the stage:
PS > $a = 8
PS > $b = 6
PS > $a / $b
1.3333333333333

One way is to use the format string approach.
 
PS > "{0:n2}" -f ($a / $b)
1.33

So "{0:n2}" denotes a formatted string, where the 2 is how many decimal places to show.  After the -f, you put your expression to format.  There are other choices for this formatted string, which I will not detail here.  The point is that your output is a string.

Another way is to use the Math .NET class to Round.
PS > [Math]::Round(($a / $b), 2)
1.33

This time, however, you get a Double instead of a string. 

It looks like PowerShell does a great job at sorting number strings as numbers.  So far, it doesn't matter which way you use above; Sort-Object puts the numbers in the right order.  PowerShell even lets you do Math operations on numbers stored as strings!  Isn't it great?