mediumLogic ErrorsJavaScript
The float surprise
A developer asked an AI assistant to validate that a shopping cart's line-item prices sum exactly to the order total before allowing checkout. The suggested equality check fails randomly on orders that are, by every human measure, correct.
checkout.js
function totalsMatch(lineItems, expectedTotal) {
const sum = lineItems.reduce((acc, item) => acc + item.price, 0);
return sum === expectedTotal;
}
totalsMatch([{ price: 0.1 }, { price: 0.2 }], 0.3); // ?What does totalsMatch([{ price: 0.1 }, { price: 0.2 }], 0.3) actually return, and why?
false — 0.1 + 0.2 evaluates to 0.30000000000000004 in floating-point arithmetic, which is not === to 0.3.
true — JavaScript rounds decimal addition to the nearest cent automatically.
NaN — adding two decimals with different precision throws a silent type coercion error.
It throws a RangeError because floating-point numbers can't be compared with ===.