The use of php's sprintf function controls the floating point format

  • 2021-01-03 20:51:29
  • OfStack

Controls the print format of floating point numbers

The printing and formatting of floating point numbers is one of the most common functions of sprintf. Floating point numbers are controlled by the format character "%f". By default, six decimal places are reserved, such as:


sprintf("%f", 3.1415926); // Results: "3.141593"

However, there are times when you want to control the print width and the number of decimal places, you should use the "% m.nf" format, where m represents the overall width of the print number and n represents the number of decimal places. Such as:


sprintf(" %9.3f", 3.1415926); // Right aligned: Not enough digits to complete with space. Results: "    3.142"
sprintf(" %-9.3f", 3.1415926); // Left justified: space completion for insufficient digits. Results: "3.142    "
sprintf(" %.3f", 3.1415926); // The total width is not specified, the result is: "3.142"

Notice one problem


$num = 100;
sprintf("%.2f", $num );
sprintf("%.2f", (double)$num);

Are the two results really the same? It looks like one, but here's why it might be instructive.
The reason is that the user does not know that the format control corresponding to num is "%f". At the time of execution, the function itself does not know that it was an integer pushed on the stack, so the four bytes of the poor $num integer were arbitrarily forced to be interpreted as a floating point number, and the whole mess is complete.


Related articles: