Printf() and variable length precision

Formatting floating point numbers is usually best served with printf(). This example will print Pi to two decimal places:

printf("%0.2f", 3.14159265);

If you want to control how many digits of precision printf() uses you can use the * variable in your format

printf("%0.*f", 4, 3.14159265);

This example will print Pi with four digits of precision. The * substitution is used like a regular parameter, and printf() uses it in the order it receives it.

Note: This does not work with the PHP implementation of printf()

Leave A Reply
All content licensed under the Creative Commons License