Double precision double
What you'll learn: How to use the double type to store large or highly precise decimal numbers in C.
In our last lesson, we looked at float. While float is great for simple decimals, it is a bit like using a ruler that only has markings for centimeters. It gets the job done for rough estimates, but if you are trying to measure the thickness of a human hair, you need something more precise. In C, that tool is the double.
Twice the Detail
The name double is short for "double precision." In computer memory, a double typically uses 64 bits of space, which is exactly twice as much as a standard float.
Think of it like a digital notepad. If a float gives you one small sticky note to write down a number, a double gives you a full sheet of paper. With that extra space, you can store many more digits after the decimal point (usually up to 15 or 17 digits) without the computer "rounding off" your number prematurely.
When to use Double
In modern programming, double is actually the default choice for decimals. Unless you are working on a tiny device with almost no memory (like a microwave controller) or processing millions of numbers at once, you should reach for double first. It minimizes "rounding errors"—those tiny mathematical hiccups that happen when a computer runs out of room to store a long decimal.
Coding with Doubles
When you print a double using printf, you use the same %f placeholder as a float. However, if you want to see that extra precision, you can tell C exactly how many decimal places to show.
#include <stdio.h>
int main() {
// We define a double just like an int or float
double pi_precise = 3.141592653589793;
// By default, %f shows 6 digits.
// .15 tells C to show 15 digits after the decimal.
printf("Standard float view: %f\n", pi_precise);
printf("Double precision view: %.15f\n", pi_precise);
return 0;
}
In the code above, the double keeps those extra digits safe. If you tried this with a float, the number would start becoming inaccurate after the 6th or 7th digit because the "sticky note" simply ran out of room.
Key takeaway
Use double for decimal numbers to get higher precision and avoid rounding errors in your calculations.