Reputation: 2062
Jasmine has very short documentation; often it's enough. Not always.
I want to know what is exactly the second parameter of toBeCloseTo. Official reference only shows:
it("The 'toBeCloseTo' matcher is for precision math comparison", function() {
var pi = 3.1415926, e = 2.78;
expect(pi).not.toBeCloseTo(e, 2);
expect(pi).toBeCloseTo(e, 0);
});
OK it is precision, but what practically means "precision" in this case? Is it the number of digits after the "." that should be the same?
My case: i want to compare two timestamps in milliseconds; if the difference between them is less than 100, it's fine for me.
As example, what's the value of X in the following case?
var timestamp1 = 1501254807000;
var timestamp2 = 1501254807099;
var timestamp3 = 1501254807100;
var precision = X;
expect(timestamp1).toBeCloseTo(timestamp2, precision); //this should pass
expect(timestamp1).toBeCloseTo(timestamp3, precision); //this should NOT pass
If the precision is only for decimal numbers, I could divide my integers by 1000 to get decimal numbers, but anyway, I don't know what is X. For now, I do in this way:
expect(Math.abs(timestamp2-timestamp1)).toBeLessThan(100);
but it's not very readable, and I would like to use toBeCloseTo (since it exests...).
Thanks
Edit. The following results may help:
expect(1000000.005).toBeCloseTo(1000000.000,3); //fails
expect(1000000.005).toBeCloseTo(1000000.000,2); //fails
expect(1000000.005).toBeCloseTo(1000000.000,1); //pass
Upvotes: 21
Views: 14377
Reputation:
Here is an example from Jest documentation that helped me better understand value of toBeCloseTo
matcher.
expect(0.1+0.2).toBe(0.3); // fails becouse it's 0.30000000000000004
expect(0.1+0.2).toBeCloseTo(0.3); // pass
Upvotes: -3
Reputation: 483
As was stated by @Nikolaj, the "precision" parameter specifies the number of decimal places that the matcher will check precision at, with rounding.
For the examples that you've given, the first two assertions fail because, at 3 and 2 decimal places respectively, the numbers are found to be different (at 2 decimal places the trailing 05 becomes rounded to 1). At 1 decimal place the numbers are the same.
The matcher does accept a negative precision value, e.g.:
expect(1000).toBeCloseTo(1003,-1); //pass
expect(1000).toBeCloseTo(1100,-2); //fail
expect(1000).toBeCloseTo(1100,-3); //pass
But it's not very adjustable beyond that. Sadly this does mean that the matcher isn't suited for your purposes, so you're probably stuck with your suggested solution.
Upvotes: 29