1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Oh, I didn't realise that was an option. Thanks \$\endgroup\$ – Roshan Bhumbra Feb 26 '17 at 15:15
  • \$\begingroup\$ I have noticed however that this does seem to truncate rather than round. \$\endgroup\$ – Roshan Bhumbra Mar 4 '17 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.