Formatting Numbers (Part 1)

by Jan 29, 2018

The following Get-DisplayFileSize function takes any byte value and returns a nicely formatted size, using units like “MB”, “GB”, or “PB”:

function Get-DisplayFileSize 
{
    param([Double]$Number)
 
    $newNumber = $Number
 
    $unit = ',KB,MB,GB,TB,PB,EB,ZB' -split ','
    $i = $null
    while ($newNumber -ge 1KB -and $i -lt $unit.Length)
    {
        $newNumber /= 1KB
        $i++
    }
   
    if ($i -eq $null) { return $number }
    $displayText = "'{0:N2} {1}'" -f $newNumber, $unit[$i]
    $Number = $Number | Add-Member -MemberType ScriptMethod -Name ToString -Value ([Scriptblock]::Create($displayText)) -Force -PassThru
    return $Number
}

Here are some examples:

 
PS> Get-DisplayFileSize -Number 800
800
 
PS> Get-DisplayFileSize -Number 678678674345
632,07 GB
 
PS> Get-DisplayFileSize -Number 6.23GB
6,23 GB

What’s really interesting is that the function does not return strings. It returns the original numbers and just overrides its ToString() method. You can continue to sort, calculate, and compare:

 
PS> $n = 1245646233213
PS> $formatted = Get-DisplayFileSize -Number $n
PS> $formatted
1,13 TB
 
PS> $formatted -eq $n
True
 
PS> $formatted * 2
2491292466426
 
PS> Get-DisplayFileSize ($formatted * 2)
2,27 TB

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this year’s PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu.

Twitter This Tip! ReTweet this Tip!