C - Formatting floating point

Introduction

You can use more than the basic %f conversion character to format floating-point values.

Here's the format you typically use in the printf() function's formatting text:

%w.pf 

The w sets the maximum width of the entire number, including the decimal place.

The p sets precision. For example:

printf("%9.2f",12.45); 

This statement outputs four spaces and then 12.45.

Those four spaces plus 12.45 (five characters total) equal the 9 in the width.

Only two values are shown to the right of the decimal because .2 is used in the %f conversion character.

It's possible to specify the precision value without setting a width, but it must be prefixed by the decimal point, as in %.2f.

Demo

#include <stdio.h> 

int main() /*from  w  ww . j  av a  2  s  .  c o  m*/
{ 
    float sample1 = 34.5; 
    float sample2 = 12.3456789; 
    printf("%%9.1f = %9.1f\n",sample1); 
    printf("%%8.1f = %8.1f\n",sample1); 
    printf("%%7.1f = %7.1f\n",sample1); 
    printf("%%6.1f = %6.1f\n",sample1); 
    printf("%%5.1f = %5.1f\n",sample1); 
    printf("%%4.1f = %4.1f\n",sample1); 
    printf("%%3.1f = %3.1f\n",sample1); 
    printf("%%2.1f = %2.1f\n",sample1); 
    printf("%%1.1f = %1.1f\n",sample1); 
    printf("%%9.1f = %9.1f\n",sample2); 
    printf("%%9.2f = %9.2f\n",sample2); 
    printf("%%9.3f = %9.3f\n",sample2); 
    printf("%%9.4f = %9.4f\n",sample2); 
    printf("%%9.5f = %9.5f\n",sample2); 
    printf("%%9.6f = %9.6f\n",sample2); 
    printf("%%9.7f = %9.7f\n",sample2); 
    printf("%%9.6f = %9.6f\n",sample2); 
    printf("%%9.7f = %9.7f\n",sample2); 
    printf("%%9.8f = %9.8f\n",sample2); 
    return(0); 
 }

Result

From this output, you can see how the width value "pads" the numbers on the left.

As the width value decreases, so does the padding.

When the width specified is wider than the original value, nonsense is displayed, as shown by the last two lines of output.

Related Topic