Loading lessons...
Floating Point Numbers
Floating Point Numbers
Whole numbers aren't enough - we need fractions, prices, distances, and physics. That's where floating point numbers come in.
float and double
A floating point number has a decimal part (like 3.14159). C++ offers two common sizes:
float- 4 bytes, about 7 decimal digits of precision.double- 8 bytes, about 15 decimal digits of precision.
float pi = 3.14f;
double pi2 = 3.14159265358979;
The trailing f on the float marks it as a float (otherwise 3.14 is a double). Double is the default for decimal literals.
Scientific notation
Big and tiny numbers can use a shorthand like e notation:
double speedOfLight = 3e8; // 3 x 10^8 = 300,000,000
double small = 1.5e-3; // 0.0015
e8 means "times 10 to the 8th"; e-3 means "times 10 to the minus 3rd".
The precision gotcha
Floating point can't represent every decimal exactly. Some numbers (like 0.1) become tiny approximations, so:
double x = 0.1 + 0.2; // not exactly 0.3!
It prints something like 0.30000000000000004. This is normal and expected - don't test floating point numbers for exact equality.
When to use which
- Use double by default: precision is usually worth the extra 4 bytes.
- Use float when memory is tight (big arrays of numbers) and rough precision is fine.
- Use integers when you only ever need whole numbers.
TL;DR
floatholds ~7 decimal digits;doubleholds ~15.doubleis the default for decimal literals and the usual first choice.- Scientific notation:
3e8means 300,000,000. - Floating point numbers are approximations - never test exact equality.