views:

446

answers:

1

I have this line, which shows the minutes and seconds. But I have to add milliseconds to it as well for greater accuracy. How do I add that in this line, or is there an easier way to get the desired result?

@duration = [cd.ExactDuration/60000000, cd.ExactDuration/1000000 % 60].map{|t| t.to_s.rjust(2, '0') }.join(':'))

The exact duration type is saved in microseconds. So the first converts to microseconds to minutes, the second part is microseconds to seconds. Now I need to add milliseconds.

+2  A: 

cd.ExactDuration/1000 % 1000 should do the trick.

Of course you may also want to tweak the formatting, since that's a datum you don't want to right-justify in a 2-wide field;-). I'd suggest sprintf for string-formatting, though I realize its use is not really intuitive unless you come from a C background.

Alex Martelli
That works, is there a way to just make it precise to the last 2 digits though.For example, my last answer 00:03:109I would want 00:03:11
Ryan
Of course -- then you *DON'T* want milliseconds as you said, but rather centiseconds (hundredths of a second) -- and then you don't need to tweak your formatting;-). `((cd.ExactDuration+5000)/10000) % 100` will do it, including the rounding you now imply.
Alex Martelli
genius, thanks.
Ryan
@Ryan, if the answer solves your problem, accept it: that's THE basic bit of stack overflow etiquette!
Alex Martelli