I came across some code with a line looking like:
fprintf(fd, "%4.8f", ptr->myFlt);
Not working with C++ much these days, I read the doc on printf and its ilk, and learned that in this case 4 is the “width”, and 8 is the “precision”. Width was defined as the minimum number of spaces occupied by the output, padding with leading blanks if need be.
That being the case, I can’t understand what the point of a template like “%4.8f” would be,
since the 8 (zero-padded if necessary) decimals after the point would already ensure that the width of 4 was met and exceeded. So, I wrote a little program, in Visual C++:
// Formatting width test
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
printf("Need width when decimals are smaller: >%4.1f<\n", 3.4567);
printf("Seems unnecessary when decimals are greater: >%4.8f<\n", 3.4567);
printf("Doesn't matter if argument has no decimal places: >%4.8f<\n", (float)3);
return 0;
}
which gives the following output:
Need width when decimals are smaller: > 3.5<
Seems unnecessary when decimals are greater: >3.45670000<
Doesn't matter if argument has no decimal places: >3.00000000<
In the first case, the precision is less than width specified, and in fact a leading space is added. When the precision is greater, however, the width seems redundant.
Is there a reason for a format like that?
The width format specifier only affects the output if the total width of the printed number is less than the specified width. Obviously, this can never happen when the precision is set greater than or equal to the width. So, the width specification is useless in this case.
Here’s an article from MSDN; the last sentence explains it.