JavaScript Interview Question #184

Why can floating-point arithmetic produce unexpected results?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

JavaScript Number values use IEEE 754 binary floating-point representation. Many decimal fractions cannot be represented exactly in binary, so arithmetic can contain small rounding errors.

Detailed Explanation

JavaScript Number values use IEEE 754 binary floating-point representation. Many decimal fractions cannot be represented exactly in binary, so arithmetic can contain small rounding errors.

Code should not rely on exact equality for arbitrary floating-point calculations. For financial applications, teams often use integer minor units or a suitable decimal arithmetic solution according to domain requirements.

Code Example

const result = 0.1 + 0.2;

console.log(result);
// 0.30000000000000004

console.log(
    Math.abs(result - 0.3) < Number.EPSILON
); // true for this example