PHP and unit testing assertions with decimals

Tower picture Tower · Dec 26, 2009 · Viewed 8.3k times · Source

I have a method that returns a float like 1.234567890.I want to test that it really does so. However, it seems that this returned float has different precision on different platforms so how do I assert that the returned value is 1.23456789? If I just do:

$this->assertEqual(1.23456789, $float);

Then that might fail on some platforms where there is not enough precision.

Answer

Bernhard Wagner picture Bernhard Wagner · Jan 18, 2013

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);