Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Width and precision format specifiers for printf

According to https://cplusplus.com/reference/cstdio/printf/ the printf format specifier follows this prototype:

%[flags][width][.precision][length]specifier  

Regarding width the above-mentioned web page states:

Minimum number of characters to be printed. If the value to be printed
is shorter than this number, the result is padded with blank spaces.
The value is not truncated even if the result is larger.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the sample source code, as shown below, I have specified a width of 4 and a precision of 2, for printing the value of PI. I was expecting the output to be padded by a single blank space, to meet the field width constraint of 4, since the precision is 2. However, I am finding that the output is not padded by a single blank space.

#include <stdio.h>
#include <math.h>

int main()
{
   printf ("PI:%4.2f\n", M_PI);
   // Outputs PI:3.14, and not
   // PI: 3.14
   
   return 0;
}

>Solution :

Minimum number of characters to be printed

3.14 was printed – that’s 4 characters 3 . 1 4. If you want to print an additional space, that would be 5 characters 3 . 1 4 – so width 5.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading