1

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?

2
  • Two decimal points? How so? Commented Nov 5, 2012 at 0:34
  • That example looks like you want sprintf(). Commented Nov 5, 2012 at 0:36

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.