Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest toBeCloseTo's precision not working as expected

I'm trying to use toBeCloseTo in Jest to test a floating point number:

expect(value).toBeCloseTo(0.01491, 5);

But when I run my test, I see this result:

Precision: 5-digit
Expected: 0.01491
Received: 0.01491570355

When I set the precision to 4, the test passes, but I'm confused. In the documentation, it says:

Use numDigits to control how many digits after the decimal point to check

So, I'm assuming here that I'm comparing the correct number of digits: I have .01491, which has 5 digits, so I expect (pun intended!) the test to compare exactly those digits and pass.

What am I missing here?

Thank you

like image 338
Farzad Avatar asked Jun 17 '18 12:06

Farzad


1 Answers

The actual comparison used by Jest's toBeCloseTo method is

    Math.abs(expected - actual) < Math.pow(10, -precision) / 2

(Oddly enough the documentation lists the third parameter as numDigits, not precision.)

So your test fails because the difference between the expected value and the actual value exceeds 0.5 × 10−5: it's about 0.57 × 10−5. Rounded to five decimal places, the received value 0.01491570355 is 0.01492.

As far as I can see the logic behind a comparison such as this is that the actual value will be considered close to the expected value to within numDigits digits if the expected value is what you get from rounding the actual value to numDigits decimal places.

like image 151
Luke Woodward Avatar answered Oct 23 '22 23:10

Luke Woodward