2013-12-15 40 views
1

我有一個時間與十分之一秒存儲的運動相關。我需要格式化它們,如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); 
} 

回答

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

我不會,雖然考慮這個清潔。除了可以使用正則表達式ltrim()之外,您的代碼還可以。

+0

聰明!但是,可能並不特別乾淨:p關於'ltrim',你會設法保持最後的0,如同'0.1'一樣嗎? – Svish

+0

我會檢查'$ tenths <10'並直接返回0. $ ten。在這種情況下不需要進一步計算 –

+0

啊,當然。我覺得太複雜了:p – Svish