Question about formatting times

Hi. I have a question that I don't know if could it be possible:

I'm developing an stopwatch with stopwatch class, and the result time is in a variable (unsigned long)

what I want to do is format this number (milliseconds) in order to print it in a screen.
I have an algorithm that makes this perfectly:

      time=sw1.elapsed();
      minu=time/60000;  //minutes
      minu_ud=minu%10;
      minu_dec=(minu-minu_ud)/10;
      seg=(time/1000)-(minu*60);
      su=seg%10; 
      sd=(seg-su)/10;
      l=time-(seg*1000)-(minu*60000);
      lu=l%10;
      ld=((l-lu)/10)%10;
      lc=(l-(ld*10)-lu)/100;

The result I can print with instructions like:
lcd.print(minu_dec)
lcd.print(minu_ud)
lcd.print(":")
lcd.print(seg_dec)
lcd.print(seg_ud)
....
And the result is: 10:23:345, for example.

Now, my question is:
Would it be possible make a custom function like: formatTime(time) that returns the number with the same result?
I don't know if there is possible, because I would have to 'mix' unsigned longs with charr (":")

Any idea?

Thanks!

You could write a function which puts all the stuff into a character array, and then "print" that.

Normally this would be something like

char buf[10]
int h=10 ;
int m=23;
int s=42;
formatIt( buf, h,m,s );


void formatIt( char* b,  int h, int m, int s )
{
    sprintf(b,"%02d:%02d:%02d", h,m,s);
}

But the normal sprintf() function doesn't work on arduino, there are workarounds for that. And you would need to modify it for any decimal fractional part of the seconds.

michinyon:
But the normal sprintf() function doesn't work on arduino, there are workarounds for that. And you would need to modify it for any decimal fractional part of the seconds.

I'm not aware of any problems with it, although you're right that Arduino disables the floating point output formats.

It would be better to call snprintf() so that you get array bounds checking too. The call would then be so concise that there would be little point in putting it in its own function.

snprintf(buf, sizeof(buf), "%02d:%02d:%03d", min, sec, mil);