Convert float to HH: MM format

I have a question about formatting a string or float.

Therefore, essentially, I have these numbers that need to be output as shown:

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

Here is a function that I wrote that does a terrible job of what I need.

 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, I understand that I tried the DateTime class, but could not format the numbers correctly for using it.

Thanks.

+5
source share
3 answers

You just need sprintf to fill 0, fmod to extract the fraction and, if necessary, round , if second floors are not allowed:

 $time = 15.33; echo sprintf('%02d:%02d', (int) $time, fmod($time, 1) * 60); 
+8
source

You can do something like:

 $example = 1.3333; 

Get a fractional element of your time by doing modulo 1

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

Then you can use (int)$example or floor($example) to get the hourly component of your time.

 $hour = floor($example); echo $hour." ".$minutes; 
+1
source

Cut the whole part of the float:

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

Multiply the number of units (minutes) by a larger 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); 
0
source

Source: https://habr.com/ru/post/1209190/


All Articles