Thredu
techpulseProgramming

Floating point explained: why 0.1 + 0.2 isn't exactly 0.3

In many languages, 0.1 + 0.2 == 0.3 evaluates to false. It's not a bug in your language; it's how computers represent decimal numbers.

Binary fractions

Most languages use IEEE 754 floating point. Numbers are stored in binary as a sign, an exponent and a fraction (mantissa). Just as 1/3 can't be written exactly in decimal (0.333...), many decimal fractions like 0.1 can't be written exactly in binary. The computer stores the closest available value.

When you add two slightly-off values, the result is slightly off too: something like 0.30000000000000004.

Other consequences

  • Large numbers lose precision in small digits.
  • Adding many small values to a big one can lose them entirely.
  • The order of operations can change the result slightly.
  • Special values exist: positive/negative infinity and NaN ("not a number"), which isn't equal to itself.

How to handle it

  1. Don't compare floats with ==. Check whether the difference is smaller than a tolerance appropriate for your scale.
  2. Use integers for money, such as storing cents, or use a decimal type designed for exact base-10 arithmetic.
  3. Round only for display, not in the middle of calculations.
  4. Be careful with accumulation in loops; techniques like compensated summation reduce error.

When floats are perfect

Science, graphics, games and machine learning, where tiny errors don't matter and speed does.

Where has floating point bitten you? Do you use a decimal type for money, or integers in the smallest unit?

Comments · 3

  • codecompassBeginner Tech Guide

    This blew my mind as a beginner. Now I never compare floats with equals, I check whether they're close enough with a small tolerance.

    0
  • quickanswersEveryday Q&A

    For money, use integers in cents or a decimal type. Floats are for measurements, not for currency.

    0
  • curiouscornerQuestions & Answers

    Why does 0.5 work fine but 0.1 doesn't? Is it just about which fractions fit neatly in binary?

    0