I know printf is use for outputing and sprintf is use for storing.
But in this code:
$str = printf('%.1f', 1.3);
echo $str;
Why does it output 1.33? I assume it would output 1.31.3?
printf function in PHP does, in fact, two things: prints its arguments (according to the format string, sent as the first one) AND returns the length of this printed string.
Usually the value returned by printf
is not used - but not in this case. As (by format) printf
here had to print '1.3' string (only one digit after the decimal point), its length is 3 - so it's stored in $str
variable and gets printed in the next statement (with echo
). So the whole output is '1.33'.
As a sidenote, this...
$str = print(1.3);
echo $str;
... prints '1.31', as print also does two things - prints its arguments AND returns 1.