Reputation: 20874
I am reading through an old school (1990) book on C and they have a number formatting in it which loops like this:
...
...
printf("%3.1f %15.10f\n",x, x*x+x+1/x);
In the book it says that it
%m.kf
Converts a value of type float (or double) tom
decimal positions withk
digits after the period.
After playing around with this I am still completely baffled.
I played around with this. http://cstub.com/196059842/
#include <stdio.h>
int main( int argc, const char* argv[] )
{
double f = 1.55568;
printf("%10.12f",f);
}
1.555680824083
Upvotes: 0
Views: 15392
Reputation: 53006
Prints a floating point number with 1 precision and 3 characters minimum width, so for example
printf("%3.1f\n", 3.5);
would output
3.5
because it has 3 characters 3
.
and 5
, but
printf("%10.1f\n", 3.5);
would output
3.5
_______---
/* ^ 7 spaces because 10 characters width requested */
This would allow you to right align numbers like
printf("%10.1f\n", 3.5);
printf("%10.1f\n", 121.2);
printf("%10.1f\n", 54.7);
output
3.5
121.2
54.7
Upvotes: 4
Reputation: 73366
Check this example:
double f = 1.234;
printf("%10.2f",f); // 10 positions wide, 2 decimals at most
Output:
1.23 <- print only 2 decimal digits
^^^^^^^^^^
||||||||||
0123456789 <- positions
Such code is a bit common when you want to output statistics and you want everything to be nicely aligned.
In your example:
double f = 1.55568;
printf("%10.12f",f);
You say to print at maximum 12 digits after the period. Of course, the number has more digits than you wrote when assigning the value, because of its representation.
You also say that what gets printed should have 10 positions at the minimum, which means that if the number is not big enough, whitespaces will be placed before the number so that the requirement is met.
Upvotes: 5