PHP printf function and it's weird behaviour

后端 未结 1 749
孤街浪徒
孤街浪徒 2021-01-19 12:51

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.0         


        
相关标签:
1条回答
  • 2021-01-19 13:18

    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);
    
    0 讨论(0)
提交回复
热议问题