alia an - 2 months ago 24
PHP Question

# microtime in second with 2 decimals

I try calculate time of an act in second with 2 decimals.

``````protected function microtimeFormat(\$data)
{
\$duration = microtime(true) - \$data;
\$hours = (int)(\$duration/60/60);
\$minutes = (int)(\$duration/60)-\$hours*60;
return \$seconds = \$duration-\$hours*60*60-\$minutes*60;

}
``````

this method get start time as \$data...and get back it an int second

for example it return 2second.

I try get second with 2 decimals ...

``````protected function microtimeFormat(\$data,\$format=null,\$lng=null)
{
\$duration = microtime(true) - \$data;
\$hours = (float)(\$duration/60/60);
\$minutes = (float)(\$duration/60)-\$hours*60;
\$seconds = \$duration-\$hours*60*60-\$minutes*60;
return number_format((float)\$seconds, 2, '.', '');
}
``````

but it return me 0.00 for short time

I think your issue comes from the `(float)` conversion to `\$hours` and `\$minutes`. When you do so you don't save the decimal part of each so your calculation of `\$seconds` always give 0. Convert to `int` so you actually save in `\$hours` and `\$minutes` the actual number of seconds they each represent. And the remainder goes to `\$seconds`.

``````protected function microtimeFormat(\$data,\$format=null,\$lng=null)
{
\$duration = microtime(true) - \$data;
\$hours = (int)(\$duration/60/60);
\$minutes = (int)(\$duration/60)-\$hours*60;
\$seconds = \$duration-\$hours*60*60-\$minutes*60;
return number_format((float)\$seconds, 2, '.', '');
}

\$start = microtime(TRUE);
sleep(1);
\$delay = \$this->microtimeFormat(\$start);
var_dump(\$delay);
``````

This gives me:

``````string(4) "1.01"
``````
Source (Stackoverflow)