Lesson 33 +10 XP

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. 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 marks the literal as a float (otherwise 3.14 is a double).

Scientific notation

Big and tiny numbers can use e notation:

double speedOfLight = 3e8;     // 3 x 10^8 = 300,000,000
double small = 1.5e-3;         // 0.0015

The precision gotcha

Floating point can't represent every decimal exactly. Some numbers (like 0.1) become tiny approximations:

double x = 0.1 + 0.2;   // not exactly 0.3!

When to use which

  • Use double by default: precision is usually worth the extra 4 bytes.
  • Use float when memory is tight and rough precision is fine.

TL;DR

  • float holds ~7 decimal digits; double holds ~15.
  • double is the usual first choice.
  • Scientific notation: 3e8 means 300,000,000.
  • Floating point numbers are approximations - never test exact equality.