将十分之一设置为运动时间


Format tenths into sports time

我有一个与运动相关的时间存储在十分之一秒内。我需要像h:mm:ss.f一样格式化它们,其中每个部分只有在必要时才可见。所以一些例子:

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

你将如何在PHP中做到这一点?


这是我目前的解决方案,但想知道是否还有其他更清洁、更高效或更花哨的方法可以做到这一点?

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:');

不过我不会认为这个更干净。除了在可以使用ltrim()时使用正则表达式之外,您的代码还可以。