Why JavaScript Floating Point Math Breaks Your App (And How to Fix It) JavaScript's IEEE 754 floating point format means 0.1 + 0.2 !== 0.3 — and that's just the obvious case. This post covers why it happens, where it silently breaks production code, and four concrete strategies: toFixed for display, integer arithmetic for money, a scale-round-ceil pattern for computed floats, and decimal.js for complex chains....
The Dev World’s Post
More Relevant Posts
-
Why JavaScript Floating Point Math Breaks Your App (And How to Fix It) JavaScript's IEEE 754 floating point format means 0.1 + 0.2 !== 0.3 — and that's just the obvious case. This post covers why it happens, where it silently breaks production code, and four concrete strategies: toFixed for display, integer arithmetic for money, a scale-round-ceil pattern for computed floats, and decimal.js for complex chains....
To view or add a comment, sign in
-
Most developers learn JavaScript math like this: 👉 `0.1 + 0.2 === 0.3` But in JavaScript, that is false. And the reason is bigger than JavaScript itself: 👉 Floating point math is inherently imprecise This is not a bug. It is how computers represent decimal numbers. Some numbers cannot be stored exactly in binary, so JavaScript keeps the closest possible value instead. That is why this happens: • `0.1 + 0.2` becomes `0.30000000000000004` • `0.3 - 0.2` can produce unexpected decimals • Comparisons like `a === b` may fail when you expect them to pass This matters a lot in real code: • Money calculations • Measurements • Scientific values • Threshold checks • UI rounding bugs So the lesson is simple: Don’t assume decimal math is exact. When precision matters, round carefully, compare with tolerance, or use a numeric strategy designed for the job. JavaScript is not bad at math. It is just honest about the way computers store numbers. And once you understand that, a whole class of “weird bugs” suddenly makes sense. #JavaScript #Programming #SoftwareEngineering #WebDevelopment #CodingTips #LearnToCode #ComputerScience #FrontendDevelopment #DeveloperLife
To view or add a comment, sign in
-
-
Most JavaScript developers know V8 compiles their code. Far fewer know that when their code calls Math.random(), V8 doesn't generate the number in its main interpreter. 🤔 It hands the work to a dedicated module with its own state, its own algorithm, and a buffer of 64 pre-computed values invisible to JavaScript code. The same architectural pattern V8 uses for regular expressions, where Irregexp takes over the moment the runtime sees a /pattern/. The algorithm is xorshift128+, designed by Sebastiano Vigna in 2014. Three shifts, three XORs, one addition, on a 128-bit state. Fast enough to run at ~90 nanoseconds per call. Statistically excellent: passes BigCrush, the gold-standard test suite. And cryptographically broken by design: an attacker who observes three Math.random() outputs can recover the full internal state with a Z3 solver in under a second, then predict every future output. This is not a theoretical concern. CVE-2025-7783 (CVSS 9.4 critical, July 2025) hit form-data, a transitive dependency in millions of weekly npm downloads, because it generated multipart boundaries with Math.random(). Three observations, one Z3 query, one HTTP Parameter Pollution attack. The bug had been there for years. The deeper insight: Math.random() is not a random number generator. It is a deterministic state machine that produces the illusion of randomness. Every major engine (V8, JavaScriptCore, SpiderMonkey) converged on the same algorithm in 2015-2016. Knowing what's behind the function is the difference between code that happens to work and code we understand. The full deep dive, with Z3 code, hex traces, IEEE 754 bit-layout, tinybench numbers, and the TC39 proposals on the way: 👉 https://lnkd.in/eFYXuswp Four links worth reading alongside it: → V8's own write-up on the xorshift128+ migration: https://lnkd.in/eD4uDQJ4 → Vigna's xorshift+ paper (the algorithm itself): https://lnkd.in/eSBFszd6 → The CVE-2025-7783 advisory: https://lnkd.in/eGF5wBUW → The state-recovery PoC by PwnFunction: https://lnkd.in/eEAr3CFX https://lnkd.in/eFYXuswp Happy reading and discovering! 😊🚀📚 #javascript #nodejs #typescript #webdev #softwareengineering #security
To view or add a comment, sign in
-
🚀 Memory Management in JavaScript Most developers ignore this… until their apps start lagging 😵 Let’s understand it simply 👇 🧠 What is Memory Management? 👉 How JavaScript stores and cleans memory automatically 👉 Handled by the JavaScript engine ⚡ Memory Lifecycle: 1️⃣ Allocation 👉 Memory is allocated when variables are declared 2️⃣ Usage 👉 You read / write data 3️⃣ Release 👉 Unused memory is removed 🗑️ Garbage Collection (GC) 👉 JavaScript automatically removes unreachable memory 💡 Based on: 👉 Reachability ✔ Reachable = In use ❌ Not reachable = Garbage 🧩 Example: let user = { name: "Swapnil" }; user = null; // Now object becomes unreachable 👉 Memory is cleaned automatically 🔥 Common Memory Leaks: ❌ Unused global variables ❌ Forgotten timers (setInterval) ❌ Closures holding unnecessary data ⚡ Why it matters? 👉 Prevents: ✔ Memory leaks ✔ Slow apps ✔ Crashes 💡 One line to remember: 👉 “If nothing references it, JavaScript removes it” 💬 Did you know JavaScript handles memory automatically? 📌 Save this (advanced + interview important) #javascript #webdevelopment #frontend #coding #programming #javascriptdeveloper #learncoding #developers #100DaysOfCode
To view or add a comment, sign in
-
-
⚛️ What is a Prototype in JavaScript? This is the concept that made everything click for me. Every object in JavaScript has a hidden link: 👉 [[Prototype]] 💡 Simple example: const user = { sayHi() { console.log("Hi"); } }; const ahmed = { name: "Ahmed" }; ahmed.__proto__ = user; ahmed.sayHi(); // "Hi" Wait… ahmed doesn’t have sayHi. So how did it work? 👉 JavaScript looks up the prototype chain 🔥 What actually happens: JS looks inside ahmed Not found Goes to its prototype Finds sayHi → executes 🧠 That’s inheritance in JavaScript. Not copying code… but linking objects together. 🚀 My takeaway: Objects in JS don’t stand alone — they’re part of a chain. And understanding that chain changes everything. #JavaScript #Frontend #Programming #OOP
To view or add a comment, sign in
-
Just published a new blog on Template Literals in JavaScript: - Cleaner syntax - Easier variable embedding - Proper multi-line strings - Much better readability overall It’s one of those small concepts that actually has a big impact when you start building real projects. If you're learning JavaScript or already building, this is definitely worth mastering 👇 https://lnkd.in/gVw7vpK3 Thanks to Hitesh Choudhary, Chai Aur Code, Piyush Garg, Akash Kadlag, Jay Kadlag and Nikhil Rathore for guidance! #JavaScript #WebDevelopment #FrontendDevelopment #Coding #LearnInPublic #100DaysOfCode #Developers #Programming #SoftwareDevelopment #TechJourney
To view or add a comment, sign in
-
Ever wonder why your JavaScript code can suddenly talk to a database or manipulate files, even though it was originally built just to make buttons blink in a browser? Long before Node.js existed, there was C++. It’s the seasoned veteran fast, powerful, and capable of talking directly to your computer's hardware. But C++ is complex; it doesn’t "move" as fast as modern web developers need it to. Over at Google, engineers built the V8 Engine to make Chrome lightning fast. They used C++ to build a "translator" that could take simple JavaScript and turn it into high-speed machine code. In 2009, Ryan Dahl had a "What if?" moment. He realized he could take that V8 engine out of the browser and marry it to a C++ library called Libuv. The result? Node.js. JavaScript is the Frontman: Easy to write, friendly, and accessible. C++ is the Backstage Crew: Handling the heavy lifting, the file systems, and the networking that JavaScript can’t touch on its own. Node.js isn't just a language; it’s a power suit for JavaScript. By wrapping the speed of C++ in the simplicity of JS, it gave us the best of both worlds: developer productivity without sacrificing raw performance. Next time you run npm start, remember: you’re actually driving a C++ powerhouse, steered by the elegance of JavaScript. 🛠️✨ Do you know this before? #NodeJS #Programming #WebDevelopment #SoftwareEngineering #TechStories
To view or add a comment, sign in
-
Midweek NextPath Mag post, contributed by the Javascript diva Peter Skinner about one of the most vital, yet terrible, constructs in programming. And no, it's not npm ;) https://lnkd.in/enuEiP_m
To view or add a comment, sign in
-
Ever wondered how JavaScript handles concurrency while being single-threaded? I just published a deep dive into the Event Loop, breaking down how it works under the hood. Since this is my first article, I’m really looking forward to hearing what you think! Drop a comment with your feedback or any questions! 👇 Here is the article: https://lnkd.in/d5UWyrbE #JavaScript #WebDevelopment #SoftwareEngineering #EventLoop #CodingCommunity #Frontend #Programming
To view or add a comment, sign in
-
JavaScript's most confusing line — and it's only 15 characters Look at this carefully: typeof("6" / "abc") // → 'number' "6" / "abc" // → NaN Wait. The result is NaN — Not a Number. But typeof says it's a number? Yes. That's not a bug. That's JavaScript working exactly as designed. Here's what's actually happening: 🔹 JS tries to divide "6" by "abc" 🔹 It coerces "6" into the number 6 first 🔹 "abc" can't be coerced — becomes NaN 🔹 6 / NaN = NaN And here's the part that breaks everyone's brain: NaN is technically of type number in JavaScript. NaN = Not a Number. typeof NaN = "number". ✔️ NaN means the operation failed to produce a valid number ✔️ But the type system still classifies it as numeric type ✔️ It's an IEEE 754 floating point standard decision — not just JS ✔️ NaN === NaN returns false — NaN is not equal to itself Pro tip: Never check for NaN using === Use Number.isNaN(value) instead. It's the only reliable way. JavaScript doesn't always fail loudly. Sometimes it just quietly returns NaN and keeps moving. That silent failure is what makes JS bugs so hard to trace in real apps. Did you know NaN was typeof number before seeing this? #JavaScript #WebDevelopment #Programming #SoftwareEngineering #Frontend #JS #TechLearning
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development