简体   繁体   中英

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.

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

作为对@bernhard-wagner 答案的更新,您现在应该使用assertEqualsWithDelta() 自 phpunit 7.5

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

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.

为了获得更高的准确性,您可以考虑使用BCMath

或者使用 bcmath() 您还可以设置默认精度,如下所示:

ini_set('precision', 14);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM