Spot Floating Point Precision
Question
This code gives an unexpected result. What is the issue?
Code
const result = 0.1 + 0.2;
console.log(result === 0.3);
Hint
JavaScript uses IEEE 754 double-precision floating point.
Explanation
JavaScript uses IEEE 754 double-precision floating point, which cannot represent 0.1 and 0.2 exactly. 0.1 + 0.2 evaluates to 0.30000000000000004, so === 0.3 is false. To compare floats, use a small epsilon: Math.abs(result - 0.3) < 1e-9. For currency, use integers (cents) or a decimal library.
Related Resources
Related Lessons
- JavaScript Data Types
Learn about floating point precision.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.