Skip to content

Floating Point Comparison Failure

Error message

                Expected: 0.3, Received: 0.30000000000000004
              

Quick summary

JavaScript floating-point arithmetic is imprecise. 0.1 + 0.2 equals 0.30000000000000004, not 0.3. Using toBe for exact comparison fails.

Why this happens

  • Using toBe or toEqual for floating-point number comparison.

  • IEEE 754 double-precision floating-point representation introduces small errors.

  • Accumulated arithmetic operations amplify precision errors.

Minimal example

✗ Broken code
test('decimal', () => {
  expect(0.1 + 0.2).toBe(0.3); // fails
  // 0.1 + 0.2 = 0.30000000000000004
});
✓ Fixed code
test('decimal', () => {
  expect(0.1 + 0.2).toBeCloseTo(0.3); // passes
  // Checks within 2 decimal places by default
});

Use toBeCloseTo for floating-point comparison. It checks within a small tolerance.

How to diagnose

  • Check if the assertion compares floating-point numbers with toBe.

  • Log the actual received value to see the precision error.

  • Understand that 0.1 + 0.2 !== 0.3 in JavaScript (and most languages).

How to fix

  • Use toBeCloseTo instead of toBe: expect(0.1 + 0.2).toBeCloseTo(0.3).

  • toBeCloseTo checks equality within 2 decimal places by default (configurable).

  • For custom precision: expect(value).toBeCloseTo(expected, numDigits).

How to prevent

  • Always use toBeCloseTo for floating-point comparisons.

  • Be aware of floating-point precision issues in all languages.

Related Resources

Related Glossary

Related Lessons

← Back to language