Rounding numbers

We often need to round numbers when we are writing administration scripts – for example

PS> Get-ChildItem c:\hiberfil.sys -Force | Format-Table Name, Length -AutoSize

Name             Length
----             ------
hiberfil.sys 2213351424

 

We need the force because hiberfil.sys is a hidden file.  Looking at the file size its about 2GB but its difficult to relate to a number that size so we can try this

PS> Get-ChildItem c:\hiberfil.sys -Force | Format-Table Name, @{Name="Size";Expression={$_.Length/1GB}} -AutoSize

Name                     Size
----                     ----
hiberfil.sys 2.06134414672852

 

However there are too may numbers after the decimal point – we don’t need that level of accuracy.  The easiest way to round the numbers is to use the Math .NET class.

PS> Get-ChildItem c:\hiberfil.sys -Force | Format-Table Name,

@{Name="Size";Expression={[math]::round($_.Length/1GB,2)}}  -AutoSize

Name         Size
----         ----
hiberfil.sys 2.06

 

Which gives us a nice easy to understand display

Leave a Reply