More on Format Specifiers

We can specify the number of decimal places we want to display in the format specifier. To obtain the output to three decimal places, we would write the format specifier as %.3f. To get ten places, we would write %.10f.

#include <stdio.h>

int main(void){
 
    double num = 2.0 / 7.0;
    
    
    /*
     * specify the number of
     * decimal places
     * in the format specifier
     */
    printf("%.3f\n", num);
    printf("%f\n", num);
    printf("%.9f\n", num);
    printf("%.12f\n", num);
    
    
 
    return 0;
    
}

The field width for the output, which is the total number of characters used to display the value, is determined automatically by the printf() function. However, it is possible to determine the field width ourselves; this is useful is we want to output columns of data so that they line up. To specify a width value, place an integer before the format character.

 #include <stdio.h>

int main(void){
 
 
 
  unsigned int a = 8675309;
  int b = 73;
  double c = 27.408;
 
  printf("a = %7u\n", a);
  printf("b = %7d\n", b);
  printf("c = %7.3f\n", c);
 
  return 0;
 
}

When we specify a field width, the value will by default be right-aligned. We can left-align the field by putting a minus sign following the %.

#include <stdio.h>


int main(void){
 
  long long int a = 3135920017035;
  double b = 1138.1337;
  long double c = 3.141592653;
  char d = 112;
 
  printf("a = %-20lld", a);
  printf("b = %-20.4f\n", b);
  printf("c = %-20.9Lf", c);
  printf("d = %-20c\n", d);
  return 0;
 
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s