![](/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.