πŸ•΅οΈβ€β™€οΈ 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.
1
expect(0.1 + 0.2).toBe(0.3); // fails
2
​
3
> 0.1 + 0.2
4
0.30000000000000004
Copied!
Instead, use expect().toBeCloseTo() to validate an expected floating point value.
1
expect(0.1 + 0.2).toBeCloseTo(0.3); // passes!
Copied!
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."
1
let isClose = abs(expected - actual) < Math.pow(0.1, decimalPlaces);
Copied!
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 modified 1yr ago
Copy link