10

I have a question about formatting a string or float.

So essentially I have these numbers which need to be outputted as shown:

9.8333333333333 -> 09:50
5.5555555555556 -> 05:33
10.545454545455 -> 10:33
1.3333333333333 -> 01:20
20.923076923077 -> 20:55

Here is the function I wrote that is doing a terrible job at what I need it to.

function getTime($dist, $road) {
    $roads = array('I' => 65, 'H' => 60, 'M' => 55, 'S' => 45);
    $time = $dist / $roads[$road];
    return round($time -1) . ':' . substr((float)explode('.', $time)[1] * 60, 0, 2);
}

So if anyone has any ideas id appreciate it, i've tried the DateTime class but wasn't able to format the numbers properly for it to be used.

Thanks.

ykykykykyk
  • 446
  • 1
  • 3
  • 10

3 Answers3

23

You just need sprintf for the 0 padding, fmod to extract the fraction, and optionally round if flooring the seconds is unacceptable:

$time = 15.33;
echo sprintf('%02d:%02d', (int) $time, fmod($time, 1) * 60);
Corbin
  • 33,060
  • 6
  • 68
  • 78
  • 1
    This worked like a charm and seriously saved me! Thanks Corbin! I used the round. So here's the math I used: `sprintf('%02d:%02d', (int) $time, round(fmod($time, 1) * 60))` – cbloss793 Mar 02 '17 at 20:15
  • what if the float value is like 7.96? – mrcoder Mar 08 '22 at 12:30
1

Trim off the integer portion of the float:

$time = 9.83333333333;
$hourFraction = $time - (int)$time;

Multiply by the number of units (minutes) in the greater unit (hour):

$minutes = $hourFraction * 60;

Echo:

$hours = (int)$time;
echo str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($minutes, 2, '0', STR_PAD_LEFT);
sjagr
  • 15,983
  • 5
  • 40
  • 67
1

You could do something like:

$example = 1.3333;

Get the fractional element of your time by doing modulo 1

$remainder = $example % 1;
$minutes = 60 * $remainder;

You can then use (int)$example or floor($example) to get the hour component of your time.

$hour = floor($example);
echo $hour." ".$minutes;
Adam W
  • 126
  • 5
  • For some reason mod 1 wasn't giving me the remainder, not quite sure why. But the above did give me my answer, thanks anyways! Had the same thinking as you. – ykykykykyk Dec 16 '14 at 04:14