The use of PHP's sprintf function control floating-point number format _php instance

Source: Internet
Author: User
Tags sprintf

Control floating-point printing format

The printing and formatting control of floating point numbers is a common function of sprintf, floating-point numbers use the format character "%f" control, the default is to retain 6 digits after the decimal, such as:

Copy Code code as follows:

sprintf ("%f", 3.1415926); Result: "3.141593"

However, sometimes we want to control the width and scale of the print, and then 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. Like what:

Copy Code code as follows:

sprintf ("%9.3f", 3.1415926); Right alignment: The number of digits is not enough to complete with spaces. Result: "3.142"
sprintf ("%-9.3f", 3.1415926); Left-aligned: the number of digits is not enough to complete with spaces. Result: "3.142"
sprintf ("%.3f", 3.1415926); Do not specify total width, result: "3.142"

Pay attention to a problem

Copy 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 for this is that the caller does not know that the format control character corresponding to Num is a "%f" when the parameter presses the stack. The function is not aware of the execution of the stack is a whole number of times, so the poor save the integer $num of the 4 bytes were use robust reporting forced as a floating-point format to explain the whole mess.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.