Floating-Point Variants: Precision and Size
While double is the default for floating-point numbers, C++ gives you two other types: float and long double. The differences between them come down to precision, meaning how accurately they can represent a value.
Understanding floating-point precision
Floating-point numbers are stored as approximations. Your computer works in binary, and most decimal fractions have no exact binary representation, similar to how 1/3 has no exact decimal representation. The computer stores the closest value it can fit.
Precision is how close that approximation is. A type with higher precision stays accurate further into the decimal places. In the table below, “~7 significant digits” means the type is accurate to roughly the first 7 digits, ignoring any leading zeros. After that, the digits are unreliable.
Comparing the three types
They differ mainly in size and how many digits they preserve:
| Type | Typical Size | Significant Digits |
|---|---|---|
float | 4 bytes | ~7 |
double | 8 bytes | ~15–16 |
long double | 8–16 bytes | ~18–19 (varies by platform) |
double is the default and the right choice for almost all general-purpose work. float saves memory at the cost of precision and is mainly used in graphics and signal processing. long double is used when you need the highest precision available, such as in scientific or financial software doing sensitive numerical work.
You can see the precision difference directly:
You’ll notice this pattern in the output:
float: 3.14159274101257
^^^^^^^ matches, then drifts
double: 3.14159265358979
^^^^^^^^^^^^^^^ stays accurateThe float matches the true value for about 7 digits, then starts drifting. The double stays accurate for 15.
The f suffix on line 5 tells the compiler to treat that value as a float. Without it, the value is treated as a double, and assigning it to a float variable produces inaccuracies because of the loss in precision.
Floating-point is always approximate
Because every floating-point value is an approximation, arithmetic on them is also approximate. Small errors accumulate across calculations. For anything involving money, storing values as integer cents rather than decimal dollars is the standard approach.
Choosing the right floating-point type
Most of the time, the choice is straightforward:
doublefor almost everything.floatwhen memory or performance is a constraint, such as in graphics or signal processing.long doublewhen you need the highest precision available, such as in scientific or financial software.