Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

float, double and long double

float 12 minFloating-point types represent a finite set of values and approximate many real numbers. Their precision and range depend on the implementation; comparisons must suit the calculation and its error bounds.

c / float, double and long double

Explore each scene at your own pace.

01 · The rule

The rule

float, double and long double

Floating-point types represent a finite set of values and approximate many real numbers. Their precision and range depend on the implementation; comparisons must suit the calculation and its error bounds.

Compare precision and range without assuming decimal fractions are represented exactly.

The logger stores each reading in tenths, but the daily average rarely lands on a neat tenth: 644 tenths over 3 readings is 21.4666… degrees. For values with fractions, C has three floating-point types. They are fast and useful, and they are all approximations.

The rule

Use double by default; floats approximate, so never test them with ==.

Type Typical size Typical precision Literal
float 32 bits about 6–7 significant digits 21.5f
double 64 bits about 15–16 significant digits 21.5
long double 64 to 128 bits at least as precise as double 21.5L

On almost every machine today, float and double follow the IEEE 754 standard. long double varies most: it is an 80-bit extended format with GCC on x86 Linux, but the same as double with Microsoft's compiler.

Key facts:

  • An unsuffixed literal like 21.5 is a double. Add f to get a float.
  • printf uses %f for both float and double, because a float argument is promoted to double. scanf does not promote: it needs %f for a float and %lf for a double. For long double, both use %Lf.
  • Most decimal fractions, such as 0.1 and 21.3, have no exact binary form. The stored value is the nearest one available, so small errors creep in and add up.
double avg = 644 / 3.0;          /* 214.666..., in tenths */
printf("%.2f\n", avg / 10.0);    /* prints 21.47 */

float saves memory, which matters when you store thousands of values on a small board, but it is not "simpler" or more accurate. Reach for it deliberately.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.