Programming foundations

Stage 3 · Lesson 4 of 9

Floating point numbers

How computers run your code

Decimals are usually stored as floating point numbers: a sign, an exponent and a binary fraction, 64 bits in a double. Think of 1/3, which cannot be written exactly in decimal. In the same way, 0.1 cannot be written exactly in binary.

So 0.1 + 0.2 gives 0.30000000000000004, and 0.1 + 0.2 == 0.3 is false. The errors are tiny, but they add up in and break equality checks. Compare floats with a tolerance, a small allowed difference, such as abs(a - b) < 1e-9.

Never store money in a float. Use whole cents in an integer, or a decimal type such as Python's Decimal, Java's BigDecimal or C#'s decimal. This answers the first part of the milestone.

A question to check yourself, an AI practice session and 1 cheat sheet entry come when you add the roadmap to your account. Add it

Resources for this stage

Start with· follow one of these

Keep handy

  • Quick explanations of OS basics like processes and memory when a lecture skips a step

Also worth your time

  • Everything from a key press to a rendered page; read it after this stage

Mark this stage as not done?