Floating Point Precision
JS · Common Mistakessyntax
// 0.1 + 0.2 !== 0.3example
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
// FIX 1: Compare with tolerance
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
return Math.abs(a - b) < epsilon;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true
// FIX 2: Work in integers (cents instead of dollars)
const priceInCents = 199; // $1.99
const total = priceInCents * 3; // 597 cents = $5.97Note All numbers in JavaScript are 64-bit floating point (IEEE 754). For financial calculations, use integer arithmetic (cents) or a decimal library.