2

I tried using the assertEquals method on a float and eclipse says that the method was depreciated. Therefore, is the following alternative acceptable?

Assert.assertTrue("Total does not match expected total :",
                                            receipt.getTotal() == 32.19f);

Is there a specific reason why assertEquals must not be used to compare two floats or doubles in a test?

In general, what is the best way to assert the equality of two decimal values in JUnit. I am using the 4.10 release of JUnit

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82

1 Answers1

4

In general you can compare primitive types with ==, but with floating point values, two values can look the same (when formatted as a string) but be two different values. You should be using assertEquals(expected, actual, delta). See the answer to JUnit: assertEquals for double values.

Because double (and float) calculations are not necessarily exact, you can compare using a delta (effectively a margin of error).

Community
  • 1
  • 1
Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171