Is there a printf
width specifier which can be applied to a floating point specifier that would automatically format the output to the necessary number of s
No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.
The maximum precision of float
and double
is variable, and dependent on the actual value of the float
or double
.
Recall float
and double
are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.
For example, float
can easily distinguish between 0.0 and 0.1.
float r = 0;
printf( "%.6f\n", r ) ; // 0.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // 0.100000
But float
has no idea of the difference between 1e27
and 1e27 + 0.1
.
r = 1e27;
printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000
This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.
The %.f
modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf
can't/doesn't handle that for you.