๐Ÿ•ต๏ธโ€โ™€๏ธ toBeCloseTo

Check if a float is between a delta.

When doing floating point math, it's possible that values will not be exactly as expected because of floating point error.

expect(0.1 + 0.2).toBe(0.3); // fails

> 0.1 + 0.2
0.30000000000000004

Instead, use expect().toBeCloseTo() to validate an expected floating point value.

expect(0.1 + 0.2).toBeCloseTo(0.3); // passes!

Reference values and integer values will result in a runtime error, because toBeCloseTo comparisons require a floating point number to work.

This method also checks to make sure the provided float value matches up to a certain number of decimal places. The following formula is used to detect when float values are "close."

let isClose = abs(expected - actual) < Math.pow(0.1, decimalPlaces);

if this method is called on anything other than a f64 | f32 type, it will result it a compile time error.

This method is safe to use portably with jest.

Last updated