powershellformat

Format a decimal with both leading and trailing 0's


Both ChatGPT & Copilot have failed me. I am seeking to add padding to a time that gives me two digits for whole seconds and three digits for fractional seconds. So, given $time which is produced by

$timer = [Stopwatch]::StartNew()
$timer.Stop()
$time = $timer.Elapsed.TotalSeconds

AI suggests things like

$time = [Math]::Round($time, 3)
$time = "{0:000.000}" -f $time

When I try to use the resulting time like this

"$($time): $function"

I get a single 0 to the left of the decimal, and no trailing zeros added.

Where am I (and AI) going wrong?


Solution

  • Using the format string 00.000 is indeed correct, but since you're assigning the resulting string back to $time (which appears to have a [double] type attribute attached) it gets parsed and converted back to a [double] immediately, which is why it suddenly renders as just 0 when you later use it in an expandable string.

    Assign the output from the -f operation to a variable that isn't [double]-typed and it'll work just fine:

    $timer = [Stopwatch]::StartNew()
    $timer.Stop()
    [double]$time = $timer.Elapsed.TotalSeconds
    
    $timestamp = '{0:00.000}' -f $time
    
    "${timestamp}: ... is how long it took"