PHP and unit testing assertions with decimals

In general, it's a bad idea to test built-in floats for equality. Because of accuracy problems of floating point representation, the results of two different calculations may be perfectly equal mathematically, but different when you compare them at your PHP runtime.

Solution 1: compare how far apart they are. Say, if the absolute difference is less than 0.000001, you treat the values as equal.

Solution 2: use arbitrary precision mathematics, which supports numbers of any size and precision, represented as strings.


So far it hasn't been mentioned that assertEquals supports comparing floats by offering a delta to specifiy precision:

$this->assertEquals(1.23456789, $float, '', 0.0001);

Thanks to @Antoine87 for pointing out: since phpunit 7.5 you should use assertEqualsWithDelta():

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);

As an update to @bernhard-wagner answer, you should now use assertEqualsWithDelta() since phpunit 7.5.

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);