Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and unit testing assertions with decimals

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.

like image 730
Tower Avatar asked Dec 26 '09 10:12

Tower


2 Answers

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);
like image 119
Bernhard Wagner Avatar answered Oct 14 '22 10:10

Bernhard Wagner


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

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);
like image 7
Antoine87 Avatar answered Oct 14 '22 10:10

Antoine87