Single precision float
What you'll learn: How to store and work with decimal numbers using the float data type.
Up until now, we have dealt with whole numbers like 5, -10, or 42. But the real world isn't always so neat. If you are calculating a bank balance, a GPS coordinate, or a player's movement speed in a game, you need numbers with fractional parts. In C, the most common way to handle these is with a "floating-point" number.
The float keyword
To store a decimal, we use the float keyword. Think of a float as a container that is specially designed to hold a decimal point that can "float" between digits. This allows the computer to represent very large numbers (like the distance to a star) or very small numbers (like the width of a cell) using the same amount of memory.
In C, a float typically takes up 4 bytes of memory. Because space is limited, it provides "single precision," meaning it is accurate to about 7 decimal digits. If you need a hundred decimal places for a high-level physics simulation, a float might not be enough, but for most everyday programming tasks, it is the perfect tool for the job.
Writing floats in code
When you assign a value to a float, it is a good habit to add an f suffix to the number. This tells the C compiler, "Hey, treat this specific value as a float." Without it, C might treat the number as a more memory-heavy double by default.
To print a float using printf, we use the %f format specifier.
#include <stdio.h>
int main() {
// Declaring a float for a price
float price = 19.99f;
// Declaring a float for a measurement
float pi = 3.14159f;
printf("The item costs: $%f\n", price);
printf("The value of pi is approximately: %f\n", pi);
return 0;
}
Why "Single Precision"?
Imagine you have a small sticky note to write down a number. If the number is 1.23456789, you might run out of room and have to stop at 1.234567. That is essentially what "single precision" means. It gives you a great balance between speed and accuracy, but it isn't infinite. For most apps, games, and tools, this 7-digit accuracy is exactly what you need.
Key takeaway
Use the float type and the %f specifier to handle decimal numbers when you need a balance of memory efficiency and fractional precision.