Search⌘ K

Discussion: Count the Digits

Explore the intricacies of printf formatting for floating point numbers in C, focusing on width, precision, and rounding. Understand how to use the M_PI constant and how to interpret printf's return value to count output characters accurately.

Run the code

Now, it's time to execute the code and observe the output.

C
#include <stdio.h>
#include <math.h>
int main()
{
printf("%2.4f\n", M_PI); /* M_PI = 3.14159265358979323846 */
return(0);
}

Understanding the output

The defined constant M_PI is declared in the math.h header file. It represents the value of π out to 20 digits. Any floating point value could be specified in the printf() statement, though M_PI represents a known value with oodles of digits after the decimal.

The %2.4f placeholder directs the printf() statement to output a floating point value in a width of six digits: a minimum of two to the left of the decimal and four to the right. Because only one digit is to the left of the decimal, one character is output; a space isn’t added. For the right of the decimal, only four digits are ...