JavaScript Floating Point Math Gotchas

🤔 Quick JavaScript Challenge! What does this return? 0.1 + 0.2 === 0.3 If your answer is true, you might want to sit down for this one 😄 👉 It actually returns false. 0.1 + 0.2 // 0.30000000000000004 💡 Why does this happen? JavaScript uses floating-point arithmetic (IEEE-754) to store numbers. Some decimals like 0.1 and 0.2 can’t be represented exactly in binary, so they’re stored as very close approximations. When added together, the tiny errors show up. It’s not a bug — it’s how computers handle floating numbers! 🚀 What this teaches us as developers ✅ Never blindly trust floating-point math ✅ Use rounding when needed (toFixed, Math.round) ✅ Compare with a tolerance (Number.EPSILON) ✅ For finance apps, store values as integers (like cents) Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON 😄 Fun thought: If 0.1 + 0.2 isn’t 0.3, imagine what other “simple truths” in coding are secretly complicated. That’s what makes programming fun — always something new to learn! #ReactJS #JavaScript #WebDevelopment #Frontend #MERN #ReactHooks #CleanCode #JavaScript #WebDevelopment #FrontendMagic #CodeWithFun #TechExplainedSimply #mernstack #mern #react #js #JavaScript #WebDevelopment #CodingHumor #FrontendDevelopment #TechEducation #ProgrammingFun #LearnToCode #CodeNewbie #DeveloperCommunity

To view or add a comment, sign in

Explore content categories