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);
}
$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.