0

I currently learning the C programming language and I am not sure of what the width in a float is?

I have changed the precision of the float already and it added 0 after the . and when I changed the value of the width it just added blank spaces behind

    new_price = price + increase;
    printf("New price is %4.2f", new_price);
    return 0;
oxr463
  • 1,573
  • 3
  • 14
  • 34
  • Can you include the rest of this program, and the output created when running it? – oxr463 Aug 25 '19 at 23:17
  • 1
    The "_width of a float_" (which is a number if bits) is not the same thing as the "_width field of a floating point format specifier_" (which relates to the number of characters output, and is in any case associated with a `double` in any case). What is it about the documentation that is unclear? "_Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces._". – Clifford Aug 25 '19 at 23:32
  • 1
    It does what you asked it to do. What we can't see is what you want it to do. – Hans Passant Aug 26 '19 at 00:17
  • Possible duplicate of [Printf width specifier to maintain precision of floating-point value](https://stackoverflow.com/questions/16839658/printf-width-specifier-to-maintain-precision-of-floating-point-value) – phuclv Aug 26 '19 at 04:26
  • when in doubt, read [`printf` documentation](https://en.cppreference.com/w/cpp/io/c/fprintf) – phuclv Aug 26 '19 at 04:27
  • Sidenote: You should never use binary floating point types to store monetary values. – user694733 Aug 26 '19 at 05:10

1 Answers1

1

The 4 in "%4.2f" is the width. It directs printf() to add spaces per:

If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left ...

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256