Kar

Kar started this conversation 1 week ago.

Floating Point Precision Errors in JavaScript: Unexpected Math Results

When performing operations like 0.1 + 0.2 or multiplying decimals, the results aren’t what I expect. For example: js Copy code console.log(0.1 + 0.2); // 0.30000000000000004 instead of 0.3 Why does this happen, and how should I handle it?

Digiaru

Posted 1 week ago

JavaScript uses IEEE 754 double-precision floating-point, which can't exactly represent many decimal fractions (like 0.1 or 0.2), leading to rounding errors during arithmetic Reddit+5DEV Community+5Sling Academy+5RedditReddit. These issues often appear in financial apps or UI-calculations when precision matters Sling Academy+1LinkedIn+1. Solutions: • Use an epsilon comparison for equality: js Copy code const epsilon = 1e-6; function equal(n1, n2) { return Math.abs(n1 - n2) < epsilon; } • For exact decimal math, use libraries like Decimal.js or Big.js: js Copy code const Decimal = require('decimal.js'); const result = new Decimal(0.1).plus(0.2); console.log(result.toNumber()); // 0.3 • In unit tests (e.g. Jest), prefer methods like toBeCloseTo() instead of toBe() to handle floating point tolerance Sling Academy+1Medium+1whereisthebug.com+1Stack Overflow+1GitHub.