Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two objects with float values in jasmine?

I need to do some expectation in Jasmine, like:

let realValue = callSomeMethod();
let expected = [{
    total: 33,
    saved: 1.65
}];
expect(realValue).toEqual(expected);

But it fails, and the message is:

Expect [ Object({ total: 33, saved: 1.6500000000000001 })] 
to equal [Object({ total: 33, saved: 1.65 })].

How can I do the right checking?

like image 779
Freewind Avatar asked Jul 21 '16 15:07

Freewind


People also ask

How do you compare two float values?

To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Can we use == to compare two float or double numbers?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

Why do we never use == to compare floating point numbers?

Because floating point arithmetic is different from real number arithmetic. Bottom line: Never use == to compare two floating point numbers. Here's a simple example: double x = 1.0 / 10.0; double y = x * 10.0; if (y !=

Can we compare float and int in Java?

Yes. It's safe. Note it's a double rather than a float here - but the same rules apply.


2 Answers

The toBeCloseTo matcher is for precision math comparison:

expect(1.6500000000000001).toBeCloseTo(1.65, 2);
expect(1.6500000000000001).toBeCloseTo(1.65, 15);
expect(1.6500000000000001).not.toBeCloseTo(1.65, 16);

source: Jasmine matchers

like image 108
fain182 Avatar answered Oct 03 '22 08:10

fain182


In the case some properties are floats and some are not:

let realValue = callSomeMethod();
let expectedFloat = {
    saved: 1.65,
    otherFloat: 6.44
}
let expectedOther = {
    firstName: 'Paul',
    total: 33,
};
let expected = {
    ...expectedFloat,
    ...expectedOther
}

let floatNames = Object.getOwnPropertyNames(expectedFloat);
const testFloatProperty = (name) => () => { 
    expect(realValue[name]).toBeCloseTo(expectedFloat[name], 3)
}

for (let i in floatNames) {
    it('should be close to expected ' + floatNames[i], testFloatProperty(floatNames[i]));
}

it('should contain other expected props', function() {
    expect(realValue).toEqual(jasmine.objectContaining(expectedOther))
})
like image 28
klode Avatar answered Oct 03 '22 09:10

klode