How does the .sprintf ("% 4.2f", value) function in PHP?

I am working on several PHP tutorials, in particular DevZone PHP 101 , and it confuses me:

echo .sprintf("%4.2f", (2 * $radius * pi()))

      

I found this

I think this means that the floating point field creates four positions wide with two decimal places using the value of the first subsequent parameter.

This comes from the C / C ++ programming language string. sprintf () takes the first parameter as a format operator. Anything that starts with a% is a field specifier; everything else is just printed text. So if you give a format instruction with all text and no BOMs, it will print exactly as it appears. With format specifiers, data is required to work.

But after trying several different values ​​I still don't get it. It seems to me that the purpose of this in this case is only to limit the decimal to 2 places, which all I have to put in is

.sprintf("%.2f", (2 * $radius * pi()))

      

What is the meaning of 4 in front of it? In the PHP Manual, this leads me to believe that it specifies the total number of characters to be 4, but (a) this is not the case since the decimal point is 5 characters, and (b) it is not, because I tried to change it to a larger one number like% 8.2f and it didn't feed any zeros to either end. Can someone explain this better.

Thank!

+3


source to share


1 answer


The first number% 8 .2f in the format specifier is the padding length. By default, sprintf uses a space character.

You can see the effect with larger numbers:

printf("%20.2f", 1.23);

      

Will, for example, lead to:

                1.23

      



There should be 16 spaces before the number. The float takes 4 and the fill length is 20. (You may have printed it on a web page so no visible gaps were visible.)

And another example below on the sprintf

man page for using alternate padding characters:

printf("%'*20.2f", 1.23); // use the custom padding character '*'

      

will result in:

****************1.23

      

+7


source







All Articles