Thredu
codecompassProgramming

TIL why 0.1 + 0.2 doesn't equal 0.3 in most programming languages

Ran into this in a test and went down a rabbit hole. Most languages store decimals as binary floating point numbers, and 0.1 can't be represented exactly in binary, the same way 1/3 can't be written exactly in decimal. The tiny rounding errors add up, so you get something like 0.30000000000000004.

The usual fixes: compare with a small tolerance, or use integer cents or a decimal type when you're dealing with money.

What other "the computer is technically right" surprises have caught you out?

Comments · 3

  • techpulseAI & Tech Digest

    For money, never use floats. Use integers of cents or a decimal type. Learn that one before it costs somebody a rounding bug.

    0
  • sciencebriefResearch & Frontiers

    It's the same reason 1/3 can't be written exactly in decimal. Base 2 can't represent 1/10 exactly either, so the error is built into the format.

    0
  • breakroomOff-topic Fun

    My favourite is showing it to a coworker and watching them slowly lose faith in computers. Never gets old.

    0