60

I need to compare two values : one a string and the other is float so I convert the string to float then try to call assertEquals(val1,val2) but this is not authorized , I guess that the assertEquals doesn't accept float as arguments.

What is the solution for me in this case ?

2 Answers 2

112

You have to provide a delta to the assertion for Floats:

Assert.assertEquals(expected, actual, delta)

While delta is the maximum difference (delta) between expected and actual for which both numbers are still considered equal.

Assert.assertEquals(0.0012f, 0.0014f, 0.0002); // true
Assert.assertEquals(0.0012f, 0.0014f, 0.0001); //false
0
13

A delta-value of 0.0f also works, so for old fashioned "==" compares (use with care!), you can write

Assert.assertEquals(expected, actual, 0.0f);

instead of

Assert.assertEquals(expected, actual); // Deprecated
Assert.assertTrue(expected == actual); // Not JUnit

I like the way JUnit ensures that you really thought about the "delta" which should only be 0.0f in really trivial cases.

1
  • I would suggest using the 0.0f (including an answer edit with bold text) over the others beacause it's more semantic. I didn't know about this issue and the 0.0f could lead me to understand what's intended. With the deprecated or "Not JUnit" way it would be less obvious.
    – ElMesa
    Aug 13, 2016 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.