JUnit assertions : make the assertion between floats

lola picture lola · Sep 26, 2011 · Viewed 40.8k times · Source

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 ?

Answer

oers picture oers · Sep 26, 2011

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