Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between float and double in C/C++
In C/C++, float and double are data types used to represent floating-point numbers (numbers with a decimal part). The key difference is precision − double has twice the precision of float, which means it can represent numbers with more decimal digits of accuracy.
Precision and Storage
float uses 32 bits (1 sign bit, 8 exponent bits, 23 mantissa bits) and provides about 6–7 significant decimal digits of precision. double uses 64 bits (1 sign bit, 11 exponent bits, 52 mantissa bits) and provides about 15–16 significant decimal digits of precision.
Key Differences
| Feature | float | double |
|---|---|---|
| Size | 4 bytes (32 bits) | 8 bytes (64 bits) |
| Precision | 6–7 significant digits | 15–16 significant digits |
| Range | ±3.4 × 1038 | ±1.8 × 10308 |
| Suffix |
f or F (e.g., 3.14f) |
None needed (default for decimals) |
| Memory Usage | Less (half of double) | More (twice of float) |
Example
The following program shows the precision difference between float and double ?
#include <stdio.h>
int main() {
float f = 1.123456789012345f;
double d = 1.123456789012345;
printf("float (7 digits) : %.15f\n", f);
printf("double (15 digits): %.15f\n", d);
printf("\nSize of float : %lu bytes\n", sizeof(float));
printf("Size of double: %lu bytes\n", sizeof(double));
// Precision loss with float
float f1 = 123456.789f;
double d1 = 123456.789;
printf("\nfloat 123456.789 : %.3f\n", f1);
printf("double 123456.789 : %.3f\n", d1);
return 0;
}
The output of the above code is ?
float (7 digits) : 1.123456835746765 double (15 digits): 1.123456789012345 Size of float : 4 bytes Size of double: 8 bytes float 123456.789 : 123456.789 double 123456.789 : 123456.789
Notice how float loses accuracy after the 7th digit (1.1234568...), while double preserves all 15 digits correctly.
Conclusion
Use float when memory is limited and 6–7 digits of precision are sufficient (such as in large arrays of approximate values). Use double when higher precision is required (such as in scientific calculations, financial computations, or when accumulating many small values).
