Pre-pend a zero to single digit number strings?

I have a wave that contains one or two digit numbers (0 through 59). Mostly these are integers, but not all. I am using num2str to convert these to a string which I then concatenate with other similar strings.

I'd like to have the string read eg "07" instead of "7". Is there a way to format the string "numbers" so that 0 though 9 have a zero pre-pended but 10 through 59 don't?

So the following csv etries: 7,6,23.5 would be assemble as the string "07:06:23.5" (in other words, hours:mins:secs or degrees:mins:secs format)

At present the assembly I'm building reads "7:6:23.5"

Thanks

DN
hi!
printf "%02d", vNum


prints the number vNum with a leading zero. when using string variables you could use sprintf instead of num2str like

sprintf sString, "%02d", vNum


where now the string sString is the string representation of the single-digit number vNum with a leading zero and a two-digit number with no leading zero appended.

gregor
I think Gregor meant "%.2d". The d format specifier prints integers, which it seems is what you want for the hours and minutes. To get seconds with two digits plus fraction with a leading zero for numbers less than 10 is quite difficult.

John Weeks
WaveMetrics, Inc.
support@wavemetrics.com
Quote:
I think Gregor meant "%.2d". The d format specifier prints integers, which it seems is what you want for the hours and minutes. To get seconds with two digits plus fraction with a leading zero for numbers less than 10 is quite difficult.


Both "%02d" (use 2 digits with leading zeros) and "%.2d" (print two digits of precision) give the desired result:

Function Test(mode)
    Variable mode
   
    Variable i
    for(i=0; i<20; i+=1)
        String tmp
        if (mode == 0)
            sprintf tmp, "%02d\r", i
        else
            sprintf tmp, "%02d\r", i
        endif
        Print tmp
    endfor
End


Quote:
To get seconds with two digits plus fraction with a leading zero for numbers less than 10 is quite difficult.


I would handle the fractional part separately. Here is my attempt:

//  Example: Print ConvertToHMSF(11*3600 + 12*60 + 13 + .14)
Function/S ConvertToHMSF(totalSeconds)
    Variable totalSeconds   // With possible fraction
   
    totalSeconds = mod(totalSeconds, 24*3600)   // Wrap around after 24 hours
   
    Variable remaining = totalSeconds
   
    Variable hours = trunc(remaining/3600)
    remaining -= 3600 * hours
   
    Variable minutes = trunc(remaining/60)
    remaining -= 60 * minutes
   
    Variable seconds = trunc(remaining)
    remaining -= seconds

    Variable frac = remaining
   
    String str
    sprintf str, "%02d:%02d:%02d.%.2d", hours, minutes, seconds, round(100*frac)
    return str 
End