![](/img/trans.png)
[英]Unit testing concept, should these assertions be splitted to be “unit”?
[英]PHP and unit testing assertions with decimals
我有一个方法可以返回像 1.234567890 这样的浮点数。我想测试它是否真的这样做了。 但是,这个返回的浮点数似乎在不同平台上具有不同的精度,所以我如何断言返回的值为 1.23456789? 如果我只是这样做:
$this->assertEqual(1.23456789, $float);
然后在某些精度不够的平台上可能会失败。
到目前为止,还没有提到 assertEquals 通过提供 delta 来支持比较浮点数来指定精度:
$this->assertEquals(1.23456789, $float, '', 0.0001);
感谢@Antoine87指出: 从 phpunit 7.5 开始,您应该使用assertEqualsWithDelta()
:
$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);
作为对@bernhard-wagner 答案的更新,您现在应该使用assertEqualsWithDelta()
自 phpunit 7.5 。
$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);
为了获得更高的准确性,您可以考虑使用BCMath 。
或者使用 bcmath() 您还可以设置默认精度,如下所示:
ini_set('precision', 14);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.