2

What is the meaning of the number between % and . in printf? Both the printf's below print the same number.

#include <stdio.h>
int main()
{
    double r = 123456.987654;
    printf("%1.2f\n", r);   // 123456.99
    printf("%5.2f\n", r);   // 123456.99
    return 0;
}
Nishant
  • 20,354
  • 18
  • 69
  • 101
  • Does this answer your question? [C: printf a float value](https://stackoverflow.com/questions/8345581/c-printf-a-float-value). (Especially https://stackoverflow.com/a/8345663/452102) – Nishant Jun 07 '20 at 15:18
  • 1
    Did you read [the manual](https://en.cppreference.com/w/c/io/fprintf)? Try a larger number (`20`?) to see the difference. – HolyBlackCat Jun 07 '20 at 15:18

1 Answers1

2

From cppreference printf the number between % and optional . character in a printf format specifier is:

(optional) integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)

It specifies minimum field width. If the result to be printed would have less characters than minimum field width, it would have been padded with spaces. Because the resulting string "123456.99" has 9 characters, specifying field width that is lower or equal to 9 is going to make no difference.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • i wrote printf("%5f\n", 254.3); and the output is 254.300000. I expected 254.3 because 254.3 is composed by 5 chacarters. According to https://stackoverflow.com/questions/8345581/c-printf-a-float-value/8345663#8345663 it should display 5 characters. – Federica Guidotti Jun 07 '20 at 15:39
  • 1
    `I expected 254.3` default precision is 6. If you want one precision (ie. one digit after the comma), specify it. `because 254.3 is composed by 5 chacarters.` that's strange assumption. As said, the number specifies __minimum__ field width. The value is never truncated. – KamilCuk Jun 07 '20 at 15:41
  • @FedericaGuidotti "I expected 254.3 because 254.3 is composed by 5 chacarters." --> `double` can encode about 2^64 different values exactly. 254.3 is not one of them. Instead a nearby value was used which when written fully in decimal is more like "254.30000000000001136..." Printing that with `"%5f"` rounds to 254.300000. – chux - Reinstate Monica Jun 07 '20 at 17:50