Stage 3 · Lesson 4 of 9
Floating point numbers
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
- CourseFreeCS50: Introduction to Computer Science
Harvard University · Beginner
Weeks 0, 1, 2 and 4 teach C, arrays and memory; the difficulty is the point
- VideoFreeCrash Course Computer Science
CrashCourse · Beginner
Short free videos from logic gates to operating systems; episodes 1 to 20
Keep handy
Also worth your time
- What Happens WhenGo deeper
Everything from a key press to a rendered page; read it after this stage