Php sprintf function usage
This article mainly introduces the usage of php sprintf functions. For more information, see
Control floating point print format
The printing and format control of floating point numbers is a common function of sprintf. Floating Point Numbers are controlled by the format character "% f". By default, the six digits after the decimal point are retained. For example:
The Code is as follows:
Sprintf ("% f", 3.1415926); // Result: "3.141593"
However, sometimes we want to control the print width and decimal places, we should use: "% m. nf "format, where m indicates the overall width of the print number, n indicates the number of digits after the decimal point. For example:
The Code is as follows:
Sprintf ("% 9.3f", 3.1415926); // right alignment: Fill the number of digits with spaces. Result: "3.142"
Sprintf ("%-9.3f", 3.1415926); // left alignment: Fill the number of digits with spaces. Result: "3.142"
Sprintf ("%. 3f", 3.1415926); // The total width is not specified. Result: "3.142"
Pay attention to one problem
The Code is as follows:
$ Num = 100;
Sprintf ("%. 2f", $ num );
Sprintf ("%. 2f", (double) $ num );
Are the two results the same? Although it looks the same, the following reasons may be enlightening.
The reason is that the caller does not know that the format controller corresponding to num is "% f" when the parameter is pressed ". When a function is executed, the function itself does not know that the number pushed to the stack in the current year is an integer, so the four bytes that saved the integer $ num were forcibly interpreted as a floating-point number format.