Round fractional seconds of MySQL Time I've written a method to round a MySQL Time to two decimal places. Here's some examples:



Input           -&gt; Output

13:04:27.127930 -&gt; 13:04:27.13
00:00:14.000000 -&gt; 00:00:14.00
02:19:03.300000 -&gt; 02:19:03.30
07:13:00.954639 -&gt; 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.



&lt;?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           -&gt; Desired Output -&gt; My Output
00:00:00.995000 -&gt; 00:00:01.00    -&gt; 00:00:00.00
Why not just cast the field to lesser precision when querying from the database?

For example:

SELECT CAST(time_field AS TIME(2)) FROM table