Control floating-point printing format
The print and format control of floating-point numbers is a common feature of sprintf, and floating-point numbers use the format "%f" control, which retains 6 digits after the decimal point by default, such as:
Copy CodeThe code is as follows:
sprintf ("%f", 3.1415926); Result: "3.141593"
However, sometimes we want to control the width and scale of the print, we should use: "%M.NF" format, where m represents the overall width of the printed number, n represents the number of digits after the decimal point. Like what:
Copy the Code code as follows:
sprintf ("%9.3f", 3.1415926); Right alignment: The number of digits is not sufficient to complete the space. Result: "3.142"
sprintf ("%-9.3f", 3.1415926); Left-justified: the number of digits is not sufficient to fill with blanks. Result: "3.142"
sprintf ("%.3f", 3.1415926); Total width not specified, result: "3.142"
Pay attention to a problem
Copy the Code code as follows:
$num = 100;
sprintf ("%.2f", $num);
sprintf ("%.2f", (double) $num);
Are the two results really the same? Although it looks the same, the following reasons may be instructive.
The reason: The caller does not know that the format controller corresponding to num is a "%f" when the parameter is pressed. And the function when the function itself is not aware that the year was pressed into the stack is an integer, so poor to save the integer $num of the 4 bytes is without any explanation forcibly as a floating-point format to explain, the whole mess.
http://www.bkjia.com/PHPjc/825261.html www.bkjia.com true http://www.bkjia.com/PHPjc/825261.html techarticle control floating-point printing format floating-point number printing and format control is a common function of sprintf, floating-point numbers use the format character "%f" control, the default is reserved 6 digits after the decimal point, such as: ...