| Level Navigation: 1 | (2ℹ️) | 3 | 4 | 5 | 6 | (7ℹ️) | (8ℹ️) | (9ℹ️) | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | (37ℹ️) | 38⚡ | 39⚡ | 40⚡ | 41⚡ | 42 | 43⚡ | 44⚡ | 45 | 46 | (47ℹ️) |
When working with decimal numbers like 0.1 + 0.2, JavaScript’s floating point arithmetic can cause tiny rounding errors. We need to use toBeCloseTo() instead of toBe():
Plan: demonstrate floating point quirks by expecting add(0.1, 0.2) to be close to 0.3 rather than exactly equal.
it('should add fractions', () => {
const result = add(0.1, 0.2);
expect(result).toBeCloseTo(0.3); // Use toBeCloseTo for floating point!
});
0.1 + 0.2 becomes 0.30000000000000004). toBeCloseTo compares with a tolerance so tiny rounding errors don’t break your tests.toBeCloseTo(0.3, 5), to assert five decimal places.Try it: Add this test. Notice we use toBeCloseTo() instead of toBe()!