I've written a method to round a MySQL Time
to two decimal places. Here's some examples:
Input -> Output
13:04:27.127930 -> 13:04:27.13
00:00:14.000000 -> 00:00:14.00
02:19:03.300000 -> 02:19:03.30
07:13:00.954639 -> 07:13:00.96
My current code works, but seems a bit difficult to follow. How could I improve the readability of the code? Performance isn't too much of a concern.
<?php
public function mysql_time_to_human($mysql_time)
{
//how many decimal places it should show
(defined('DECIMAL_PLACES')) ?: define('DECIMAL_PLACES', 2);
//Separate the sting on the decimal place
$time_parts = explode('.', $mysql_time);
//Add a 0 prefix so it can properly round the decimal part
$time_parts[1] = '0.' . $time_parts[1];
//Round the number to two decimal places
$rounded_part = round($time_parts[1], DECIMAL_PLACES);
//Ensure the part is always two decimal places, including zeroes
$time_parts[1] = sprintf('%.2f', $rounded_part);
//Remove the 0 prefix added earlier
$time_parts[1] = substr($time_parts[1], 2);
//Glue the parts back together
$time = implode('.', $time_parts);
return $time;
}
While writing this question I've realized a case which my current method won't accurately work for:
Input -> Desired Output -> My Output
00:00:00.995000 -> 00:00:01.00 -> 00:00:00.00