Set printf() value in a PHP variable
Asked Answered
G

2

11

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 ?

Garver answered 11/7, 2013 at 17:21 Comment(0)
K
33

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); 
Kidney answered 11/7, 2013 at 17:30 Comment(0)
F
4

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

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

is the same as:

echo 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!

Fondle answered 11/7, 2013 at 17:35 Comment(2)
Actually, printf() is the same as echo sprintf()Therapy
@SauloPadilha Ah, I missed that. Fixed it; thanks for the heads-up!Fondle

© 2022 - 2024 — McMap. All rights reserved.