PHP printf function and it's weird behaviour

不羁的心 提交于 2019-12-31 00:57:27

问题


I'm baffled what these numbers mean. To me it seems that printf gives me wrong results.

echo printf("%.2f", 1);
// 1.004

echo printf("%.3f", 1);
// 1.005

echo printf("%.2f", 1.1234);
// 1.124

First of all it seems to print too many decimals and I have no idea what those numbers are. Can someone shed some light on this matter?


回答1:


Simple. printf() has a return value, which is integer. And that value is - length of resulting string. Thus, your code is doing two things:

  • First, format & output your string with printf()
  • Second, echo() the result, which is the length for each string.

That is because you see 1.004 for first case, for example. It's 1.00 with 4 (and length of "1.00" string is 4)

If your intention is to print formatted string, either use printf() as it is:

printf("%.2f", 1);

Or use sprintf() with echo:

echo sprintf("%.2f", 1);


来源:https://stackoverflow.com/questions/24304355/php-printf-function-and-its-weird-behaviour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!