1

I have a times related to a sport stored in tenths of a second. I need to format them like h:mm:ss.f where each portion should only be visible if necessary. So some examples:

Tenths        Formatted
          1            0.1
         12            1.2
        123           12.3
      1 234         2:03.4
     12 345        20:34.5
    123 456      3:25:45.6
  1 234 567     34:17:36.7
 12 345 678    342:56:07.8
123 456 789   3429:21:18.9

How would you do this in PHP?


This is my current solution, but wondering if there are other cleaner, more efficient or fancier ways to do this?

function sports_format($tenths)
{
    $hours = floor($tenths / 36000);
    $tenths -= $hours*36000;

    $minutes = floor($tenths / 600);
    $tenths -= $minutes*600;

    $seconds = floor($tenths / 10);
    $tenths -= $seconds*10;

    $text = sprintf('%u:%02u:%02u.%u', 
        $hours, $minutes, $seconds, $tenths);

    return preg_replace('/^(0|:){1,6}/', '', $text);
}
Svish
  • 152,914
  • 173
  • 462
  • 620

1 Answers1

0
$tenths = (array)$tenths;
$div = array(36000, 600, 10);
while($d = array_shift($div))
  $tenths[0] -= ($tenths[] = floor($tenths[0] / $d)) * $d;

$text = vsprintf('%2$u:%3$02u:%4$02u.%u', $tenths);
return ltrim($text, '0:');

I wouldn't consider this cleaner though. Except for using regular expression when you could ltrim(), your code is fine.

nice ass
  • 16,471
  • 7
  • 50
  • 89
  • Clever! But yeah, not particularly clean probably :p Regarding `ltrim` would you manage to keep the last 0 as in `0.1` though? – Svish Dec 15 '13 at 19:41
  • I would check if `$tenths < 10` and directly return 0.$tenths. No need for further calculations in this case – nice ass Dec 15 '13 at 19:44