Course contentsShow
← C
Lesson 52 of 1,2191. FoundationsFree lesson

Printing decimals with `%f`

Printing decimals with %f

What you'll learn: How to display numbers with fractional parts using the float placeholder in the printf function.

Up until now, you may have been using %d to print whole numbers (integers). But what happens when you need to talk about money, scientific measurements, or half a pizza? For numbers with decimal points, we use the float data type and a new placeholder: %f.

Meet the Floating Point

In C, numbers with decimals are called "floating-point" numbers. Think of the decimal point as a tiny buoy floating between digits. To tell printf that you want to display one of these numbers, you use the %f format specifier.

If %d stands for "decimal integer," you can think of %f as standing for "fractional" or "floating." When the computer sees %f, it prepares to output a number that includes a period and several digits after it.

Seeing it in Action

When you use %f, C defaults to showing six digits after the decimal point. This is like a high-precision scale that always shows milligrams, even if you are just weighing a heavy brick.

#include <stdio.h>

int main() {
    float pi = 3.14159;
    float price = 19.95;
    float wholeNumber = 10.0;

    printf("The value of pi is approximately %f\n", pi);
    printf("That will be $%f, please.\n", price);
    printf("Even a whole number looks like this: %f\n", wholeNumber);

    return 0;
}

The "Six-Digit" Default

In the code above, you’ll notice something interesting: 19.95 will print as 19.950000. C is very literal; it fills in those extra spots with zeros because the %f command, by default, expects a specific level of detail. Even the wholeNumber of 10.0 gets the full treatment, appearing as 10.000000.

While this might look a bit messy for a bank statement, it ensures that no precision is accidentally hidden from you. You are telling the computer, "Show me this number as a decimal," and C responds with the full standard view.

Key takeaway

Use the %f placeholder inside your printf quotes to display float variables, which will default to showing six decimal places.