C - Floating-Point Format

Number of Decimal Places

You can specify the number of places after the decimal point in the format specifier.

To obtain the output to two decimal places, write the format specifier as %.2f.

To get three decimal places, you would write %.3f.

You can change the printf() statement as follows:

printf("A plank %.2f feet long can be cut into %.0f pieces %.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 plank %.2f feet long can be cut into %.0f pieces %.2f feet long.\n",
                                       wood_length, table_count, table_length);
      return 0;/*from w w  w  . j  a va 2 s. c o  m*/
}

Result

The first format specification applies to the value of wood_length and will produce output with two decimal places.

The second specification will produce no decimal places-this makes sense here because the table_count value is a whole number.

The last specification is the same as the first.

Related Topics