Search code examples
phpfloating-pointnumbersfloating-point-precisionmicrotime

PHP microtime() conversion to microseconds


I want to get seconds and microseconds in one variable using the microtime(). If I do this:

$initial_time = microtime();
echo (explode(' ', $initial_time)[1]) . "\n";
echo (explode(' ', $initial_time)[0]) . "\n";
echo (explode(' ', $initial_time)[1]) + (explode(' ', $initial_time)[0]) . "\n";

I get:

1419714319
0.05059700
1419714319.0506 

The last line is the same as if I would have called microtime(get_as_float) or microtime(true);

How would I get the complete result 1419714319.05059700 instead of 1419714319.0506?

Thanks.


Solution

  • The number of digits displayed in a floating point number is controlled by the precision setting in the PHP.ini file. Its default value is 14 and this is exactly the number of digits you see below:

    1419714319.0506 // 10 digits before, 4 after decimal, 14 total
    

    Change this setting to a larger number::

    ini_set("precision", 20);
    $t = microtime(true);
    var_dump($t);
    // float(1419716734.0712089539)
    

    Note that this only controls the number of digits displayed, it does not affect calculations.

    Having said all that, you can still use number formatting functions to display x number of digits after decimal:

    $t1 = microtime(true);
    echo sprintf("%.20f", $t1);           // 1419717225.92410898208618164062
    echo number_format($t1, 20, ".", ""); // 1419717225.92410898208618164062