C - Floating-Point Field Width

Introduction

The general form of the format specifier for floating-point values can be written like this:

%[width][.precision][modifier]f

The square brackets here aren't part of the specification.

They enclose bits of the specification that are optional.

Thus, you can omit width or .precision or modifier or any combination of these.

The width value is an integer specifying the total number of characters in the output including spaces, so it is the output field width.

The precision value is an integer specifying the number of decimal places that are to appear after the decimal point.

The modifier part is L when the value you are outputting is type long double, otherwise you omit it.

The following code shows how to control the floating point width:

printf("A %8.2f plank foot can be cut into %5.0f pieces %6.2f feet long.\n",
                                               wood_length, table_count, table_length);

Demo

#include <stdio.h>

int main(void)
{
      float wood_length = 10.0f;               // In feet
      float table_count = 4.0f;                 // Number of equal pieces
      float table_length = 0.0f;                // Length of a piece in feet
      table_length = wood_length/table_count;
      printf("A %8.2f plank foot can be cut into %5.0f pieces %6.2f feet long.\n",
                                               wood_length, table_count, table_length);
      return 0;//  w w  w  . j a  v a 2 s .com
}

Result

Related Topic