Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set printf() value in a PHP variable

I have a php script that show a time like: 9.08374786377E-5 , but i need plain floating value as a time like : 0.00009083747..... Thats why i just print it with float like that:

<?php

function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();

$time_end = microtime_float();
$time = $time_end - $time_start;
printf('%.16f', $time);

?>

Its show the result nicely, but i need to set this printing value in a new variable. how can i do that ? I need to set this printing value in a new variable $var;

$var = printf('%.16f', $time); 

// We all know its not working, but how to set ?

like image 911
Rontdu Avatar asked Jul 11 '13 17:07

Rontdu


People also ask

Can I use printf in PHP?

Definition and Usage. The printf() function outputs a formatted string. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step".

What is difference between printf () and sprintf () in PHP?

The sprintf() function is similar to the printf() function, but the only difference between both of them is that sprint() saves the output into a string instead of displaying the formatted message on browser like printf() function.

What does %s mean in PHP?

%s is a type specifier which will be replaced to valuable's value (string) in case of %s . Besides %s you can use other specifiers, most popular are below: d - the argument is treated as an integer, and presented as a (signed) decimal number.


2 Answers

You need to use the sprintf command to get your data as a variable... printf outputs the results whereas sprintf returns the results

$var = sprintf('%.16f', $time); 
like image 86
Orangepill Avatar answered Oct 13 '22 06:10

Orangepill


That's because sprintf() returns a string, printf() displays it.

printf('%.16f', $time);

is the same as:

sprintf('%.16f', $time);

Since sprintf() prints the result to a string, you can store it in a variable like so:

$var = sprintf('%.16f', $time);

Hope this helps!

like image 34
Amal Murali Avatar answered Oct 13 '22 04:10

Amal Murali