C Programming For Beginners - Printing Double and Float

Article by Noel Kalicharan (3,085 pts ) , published Nov 23, 2008

In this article, we discuss how floating-point values are printed in C. We show what happens when we print them with and without using a “field width”.

Printing the values of double and float variables

We have been using the format specification %d in a printf statement to print the value of an integer variable. If we wish to print the value of a double or float variable, we can use %f. For example, consider:

double d = 987.654321;

printf("%f \n", d);

The value of d will be printed to a pre-defined number of decimal places (usually 6, but it could vary from one compiler to the next). In this case, the value printed will be 987.654321. However, if d were assigned 987.6543215, the value printed would be 987.654322 (rounded to 6 decimal places).

Similarly, if x was of type float, its value could be printed using:

printf("%f \n", x);

Using a field width

We just saw that the specification %f prints the number to a pre-defined number of decimal places. Most times, though, we want to say how many decimal places to print and, sometimes, how many columns to use. For example, if we want to print d, above, to 2 decimal places in a field width of 6, we can use:

printf("%6.2f \n", d);

Between % and f, we write 6.2, that is, the field width, followed by a . (point), followed by the number of decimal places. The value is rounded to the stated number of decimal places and then printed. Here, the value printed will be 987.65, which occupies exactly 6 print columns. If the field width were bigger, the number will be padded on the left with spaces. If the field width were smaller, it is ignored, and the number printed using as many columns as necessary.

As another example, consider

b = 245.75;

printf("%6.1f \n", b);

In the specification %6.1f, 1 says to round the number to 1 decimal place; this gives 245.8, which requires 5 columns for printing.

6 says to print 245.8 in 6 columns; since only 5 columns are needed for printing the number, one space is added at the beginning to make up 6 columns, so the number is printed as `245.8 (` denotes a space).

Similarly,

printf("%6.0f \n", b);

will print b as ```246 (rounded to 0 decimal places and printed in a field width of 6).

If the specification were %3.1f and the value to be printed is 245.8, it would be printed using 5 print columns, even though the field width is 3. Again, when the field width specified is smaller than the number of print columns required, C ignores the field width and prints the value using as many columns as needed.