Share via


One-Liner: Padding a Number with Leading Zeroes

I’m putting this here only because I’m tired of searching for it.  How to pad an integer with leading zeroes is trivial. 

 1..16 | % { "{0:D2}" -f $_ }

And padding a float with trailing zeroes is more of the same:

 $i = 2; (1..10) | % { "{0:F5}" -f $i; $i = $i / 2; }

Now, how about a [double] (floating point?) There may be better ways, but the only one that comes to mind is to do it string-wise:

 function Format-Float
{
    param (
        [parameter(ValueFromPipeline=$true)][double[]]$InputFloat,
        [int]$IntMinimumDigits = 3,
        [int]$FloatMinimumDigits = 3
    );
    
    process
    {
        foreach ($_inputFloat in $InputFloat)
        {
            [string]$intPortion = "{0:D$IntMinimumDigits}" -f ( 
                [int]([string]$_inputFloat -replace '\..*')
            );
            
            [string]$floatPortion = (
                "{0:F$FloatMinimumDigits}" -f $_inputFloat
            ) -replace '.*\.';
            
            "$intPortion.$floatPortion";
            
        } # foreach ($_inputFloat in $InputFloat)
    
    } # process
    
} # function Format-Float

Note that this outputs strings (the only way to keep the leading zeroes.