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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With