.toBeCloseTo(number, numDigits)
Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. For example, this test fails:
test('adding works sanely with simple decimals', () => {
expect(0.2 + 0.1).toBe(0.3); // Fails!
});
It fails because in JavaScript, 0.2 + 0.1
is actually 0.30000000000000004
. Sorry.
Instead, use .toBeCloseTo
. Use numDigits
to control how many digits after the decimal point to check. For example, if you want to be sure that 0.2 + 0.1
is equal to 0.3
with a precision of 5 decimal digits, you can use this test:
test('adding works sanely with simple decimals', () => {
expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});
The default for numDigits
is 2, which has proved to be a good default in most cases.