PHP printf function and this is weird behavior

I am puzzled by what these numbers mean. It seems to me that printf is giving me the 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 that it prints too many decimal places, and I do not know what these numbers are. Can someone shed light on this issue?

+4
source share
1 answer

Simple printf()has a return value, which is an integer. And this value is the length of the resulting string. Thus, your code performs two functions:

  • First format and output your string with printf()
  • Secondly, a echo()result that is the length for each row.

, , , 1.004 . 1.00 4 ( "1.00" 4)

, printf() :

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

sprintf() :

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

Source: https://habr.com/ru/post/1545211/


All Articles