C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial Lesson Two - Handling Numbers

By David Bolton, About.com

6 of 6

Learn how to use Format Specifiers

Format Specifiers can be enhanced with alignment, width and precision modifiers as -W.P W is the minimum field width in chars. P is the number of digits after the decimal point of a float, or number of digits of an int. A - means the output is left aligned, else it is right aligned.

Here are some examples.

#include <stdio.h>
int main() {
int a = 47;
int b = 218;
int c = 12345;
float f = 27.876;
double d = 27.876;

printf("Out %8d\n", a) ;
printf("Out %08d\n", a) ;
printf("Out %-8d\n", a) ;
printf("Out %-08d\n", a) ;

printf("Out %8d\n", b) ;
printf("Out %08d\n", b) ;
printf("Out %-8d\n", b) ;
printf("Out %-08d\n", b) ;

printf("Out %8d\n", c) ;
printf("Out %08d\n", c) ;
printf("Out %-8d\n", c) ;
printf("Out %-08d\n", c) ;

printf("Out %8.2e\n", f*f) ;
printf("Out %-8f\n", f) ;
printf("Out %-8.5f\n", f) ;
printf("Out %8f\n", f) ;

printf("Out %8.2e\n", d) ;
printf("Out %-8f\n", d) ;
printf("Out %-8.5f\n", d) ;
printf("Out %8f\n", d) ;
return 0; };

When run, this is the output

Out ......47
Out 00000047
Out 47
Out 47
Out .....218
Out 00000218
Out 218
Out 218
Out ...12345
Out 00012345
Out 12345
Out 12345
Out 2.79e+01
Out 27.875999
Out 27.87600
Out 27.875999
Out 2.79e+01
Out 27.876000
Out 27.87600
Out 27.876000
Notes periods are spaces. Note the loss of precision with the float variable f.

That completes this lesson. In lesson three, we'll start looking at chars and arrays.

Explore C / C++ / C#

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Modifying format Specifiers

©2009 About.com, a part of The New York Times Company.

All rights reserved.