0

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) to m decimal positions with k 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

5
  • 1.555680824083 has 12 digits after the decimal point -- What part is baffeling you?
    – Soren
    Jan 24, 2015 at 19:59
  • @Soren What does the 10 part do then (%10.12)?
    – Johnston
    Jan 24, 2015 at 19:59
  • @Johnston minimal field width, as with practically any similar conversion specifier. Jan 24, 2015 at 20:00
  • It is the total width of the field, but 10 is smaller than 12 so it is ignored
    – Soren
    Jan 24, 2015 at 20:00
  • 1
    I remember I had the same reaction when I saw that code for the first time, +1!
    – gsamaras
    Jan 24, 2015 at 20:14

2 Answers 2

4

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.

3

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
2
  • What is the actual use of 10 in 10.1f? Why wouldn't you just write 1 every time? What do people use that for?
    – Johnston
    Jan 24, 2015 at 20:04
  • 1
    @Johnston Suppose you want your output aligned. Jan 24, 2015 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.