Control the printing format of floating point numbers
The printing and format control of floating point numbers is a common function of sprintf. Floating point numbers are controlled using the format character "%f", and the decimal point is retained by default. 6 digits, for example:
Copy code The code is as follows:
sprintf("%f", 3.1415926); // Result: "3.141593"
However, sometimes we want to control the printed width and number of decimal places ourselves. In this case, we should use the "%m.nf" format, where m represents the overall width of the printed number and n represents the number of digits after the decimal point. For example:
Copy code The code is as follows:
sprintf(" %9.3f", 3.1415926); // Right alignment: If there are not enough digits, use spaces to complete it. Result: " 3.142"
sprintf(" %-9.3f", 3.1415926); //Left-aligned: If there are not enough digits, use spaces to complete. Result: "3.142 "
sprintf(" %.3f", 3.1415926); //Without specifying the total width, result: "3.142"
Attention to a problem
Copy the code The code is as follows:
$num = 100;
sprintf("% .2f", $num );
sprintf("%.2f", (double)$num);
Are the two results above really the same? Although it looks the same, the following reason may be enlightening.
The reason is: when the parameter is pushed onto the stack, the caller does not know that the format control character corresponding to num is "%f". When the function is executed, the function itself does not know that what was pushed onto the stack was an integer, so the poor 4 bytes storing the integer $num are forcibly interpreted as a floating point number format, and the whole thing is messed up.
http://www.bkjia.com/PHPjc/825261.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825261.htmlTechArticleControlling the printing format of floating point numbers. The printing and format control of floating point numbers is a common function of sprintf. The format of floating point numbers is used Controlled by the "%f" character, 6 digits after the decimal point are retained by default, for example:...