Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 135 ยท Variables and Types

Floating-Point Numbers

Learn how float, double and long double store numbers in C, why 0.1 + 0.2 isn't 0.3, how to compare floats safely, and how infinity, NaN and float.h work.

Whenever a number has a fractional part, like a temperature of 21.5 degrees, a distance of 3.75 km or the result of 10 / 3, you need a floating-point type. C has three: float, double and long double. They can hold enormous and tiny values, from about 10โปยณโฐโธ to 10ยณโฐโธ for a double, and the hardware computes with them very fast.

But floating-point numbers are approximations. They store a fixed number of binary digits, so most decimal fractions can't be represented exactly, and small rounding errors appear in places that surprise beginners. This lesson explains how the three types differ, where the errors come from, how to compare values safely, and how to work with the special values infinity and NaN.

float, double and long double

Type Size on our server Significant decimal digits Approximate largest value Literal
float 4 bytes 6โ€“7 3.4 ร— 10ยณโธ 2.5f
double 8 bytes 15โ€“16 1.8 ร— 10ยณโฐโธ 2.5
long double 16 bytes (80 bits used) 18โ€“19 1.2 ร— 10โดโนยณยฒ 2.5L

On almost every system, float and double follow the IEEE 754 standard (called IEC 60559 in the C standard): a sign bit, an exponent and a fraction ("mantissa"), much like scientific notation in base 2. long double varies the most: on x86-64 Linux it's the 80-bit "extended precision" format padded to 16 bytes, while on Windows with MSVC it's the same as double.

A floating literal without a suffix is a double. Add f for float and L for long double. You can also write literals in scientific notation: 6.022e23 means 6.022 ร— 10ยฒยณ, and 1e-9 is one billionth.

C Three floating types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Asking for 20 decimals reveals how many are real: float goes wrong after about 7 digits, double after about 16 and long double after about 19. Everything past that is rounding noise. %e prints scientific notation and %g picks whichever of %f or %e is shorter.

printf and scanf differ here. For printf, %f works for both float and double, because a float argument is automatically promoted to double. For scanf, the pointer types differ, so you must use %f for a float * and %lf for a double *. Use %Lf for long double in both. See Reading Input.

Why 0.1 + 0.2 is not 0.3

In decimal, 1/3 can't be written exactly: 0.3333โ€ฆ goes on forever. In binary, the same happens to 1/10. The number 0.1 becomes an infinitely repeating binary fraction, and a double stores only the closest value it can, which is very slightly more than 0.1. Add two such approximations and the tiny errors can add up to something that isn't the closest double to 0.3:

C Rounding errors you can see

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Printed with the default 6 digits, the sum looks like 0.3. With 17 significant digits (enough to show any double exactly) you see 0.30000000000000004 against 0.29999999999999999, so the comparison says "no". Adding 0.1 ten times gives 0.99999999999999989, not 1.

The last line shows the other limit: precision. A float has 24 bits of mantissa, so above 2ยฒโด = 16,777,216 it can't even represent every whole number. Adding 1 changes nothing. That's why float is a poor choice for counters, IDs or money.

These errors aren't bugs in C or in your CPU. Every language that uses IEEE 754 numbers (JavaScript, Python, Java, C++) prints the same results. The fix is to write code that expects them.

Comparing floating-point values

Because of rounding, testing two computed values with == is usually wrong. Instead, check whether they're close enough. A fixed tolerance like fabs(a - b) < 1e-9 works only when you know the values are around 1. A relative tolerance scales with the size of the numbers:

C Comparing with a tolerance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

fabs (absolute value) and fmax come from <math.h>; our editor links the math library automatically, and the Math Library lesson explains -lm for your own builds. The function combines both ideas: a relative tolerance for normal values and a small absolute tolerance for values near zero, where "one part in a billion of almost nothing" would be too strict.

There's no single correct tolerance: it depends on how many operations produced the values and how much accuracy your problem needs. 1e-9 relative is a common starting point for double.

Tip: == is fine when values are exact by construction: small whole numbers, 0.0 you assigned yourself, or powers of two like 0.5 and 0.25. Comparing for ordering (<, >) is also safe; only equality is fragile.

Infinity and NaN

IEEE 754 reserves special bit patterns for results that aren't ordinary numbers:

  • Infinity (inf, -inf): the result of overflowing the range, or of dividing a non-zero number by zero.
  • NaN ("not a number"): the result of meaningless operations such as 0.0 / 0.0, sqrt(-1.0) or inf - inf.

<math.h> defines the macros INFINITY and NAN, and the classification macros isinf, isnan, isfinite and fpclassify.

C Infinity and NaN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The sign of a printed NaN (nan or -nan) depends on the operation and the C library, so never test for NaN by looking at its text. The most surprising rule is that NaN is not equal to anything, not even itself. Every comparison with a NaN is false, except !=. Use isnan(x) to detect it. NaN also spreads: any arithmetic involving a NaN produces NaN, so one bad input can quietly poison an entire calculation. Check inputs early.

Note: The C standard itself says floating division by zero is undefined; it's IEEE 754 (Annex F of the standard) that defines it as infinity. GCC and Clang on mainstream platforms follow Annex F, which is why these results are reliable here. Integer division by zero is a different story: it's always undefined and usually crashes the program.

Converting between integers and floats

When a floating value is converted to an integer type, the fraction is truncated toward zero: (int)3.99 is 3 and (int)-3.99 is โˆ’3. If the value doesn't fit in the integer type (or is NaN or infinity), the behavior is undefined, so check the range first. To round to the nearest whole number, use round, lround or llround from <math.h>, which round halfway cases away from zero.

The other direction can lose precision too: a double holds integers exactly only up to 2โตยณ (about 9 ร— 10ยนโต), so a large long long may change slightly when stored in a double.

C Truncation versus rounding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last two lines show a classic money bug: 19.99 * 100 is actually 1998.9999999999998, so truncating gives 1998 cents. Rounding with lround gives the intended 1999. Better still, store money as whole cents from the start, as recommended in Data Types. The Type Conversions lesson covers all the conversion rules.

float.h: the limits of each type

<float.h> describes each floating type with macros prefixed FLT_, DBL_ and LDBL_. The most useful are:

Macro Meaning double value on our server
DBL_MAX Largest finite value 1.79769e+308
DBL_MIN Smallest positive normal value 2.22507e-308
DBL_EPSILON Gap between 1.0 and the next double 2.22045e-16
DBL_DIG Decimal digits that always survive a round trip 15
DBL_MANT_DIG Bits in the mantissa 53

DBL_EPSILON is the smallest number that, added to 1.0, gives a result different from 1.0. It's a measure of relative precision, not a universal tolerance for comparisons. Type Limits prints the whole set for all three types.

Choosing a floating type

  • Use double by default. It's as fast as float on modern desktop CPUs and much more accurate.
  • Use float for large arrays where memory or bandwidth matters (graphics, audio samples, machine-learning weights) or on microcontrollers without double-precision hardware.
  • Use long double rarely; its size and precision differ across platforms.
  • Never use floating-point for money or anything that must be exact; use integers.
  • Prefer formulas that avoid subtracting nearly equal numbers, where most of the significant digits cancel out.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does printf("%s", 0.1 + 0.2 == 0.3 ? "yes" : "no"); print?

    0.1 and 0.2 are stored as approximations, and their sum is the double just above 0.3 rather than the double closest to 0.3. The comparison is false.
  2. 2. double x = 0.0 / 0.0; Which test correctly detects that x is NaN?

    NaN compares unequal to everything, including itself, so x == NAN is always false. isnan(x) from <math.h> is the reliable test (and x != x is true only for NaN).
  3. 3. What is (int)-7.9?

    Converting a floating value to an integer truncates toward zero, so -7.9 becomes -7. Use floor to round down to -8, or round to round to the nearest.
  4. 4. You read a double with scanf. Which specifier is correct?

    For scanf, %f expects a float * and %lf expects a double *. printf is more forgiving because float arguments are promoted to double.
  5. 5. Why does 16777216.0f + 1.0f still equal 16777216 as a float?

    Above 2^24 the gap between neighboring floats is 2, so 16777217 can't be stored and the result rounds back to 16777216. Floats still reach about 3.4e38, just with gaps.

Summary

  • C has float (about 7 digits), double (about 16 digits) and long double (platform-dependent); unsuffixed literals like 2.5 are double.
  • Most decimal fractions can't be stored exactly in binary, so small rounding errors are normal: 0.1 + 0.2 != 0.3.
  • Compare computed values with a relative tolerance, not ==; ordering comparisons are fine.
  • Infinity and NaN are special values; NaN is unequal even to itself, so test with isnan.
  • Converting to an integer truncates toward zero; use round/lround to round. <float.h> describes each type's range and precision.
  • Use double by default, float only to save memory, and integers for money.

Next: Characters and ASCII, where you'll see that a char is really a small integer.