Skip to content

TestCase::assertSame (and related exact comparisons) must compare float exactly #4966

@mvorisek

Description

@mvorisek
Q A
PHPUnit version 9.5.10
PHP version 7.4
Installation Method Composer

Summary

Currently test case like:

 $this->assertSame(8.20234376757473, 8.20234376757474);

pass even if the numbers are different. They are really stored differently, test case:

$this->assertSame(bin2hex(pack('e', 8.20234376757473)), bin2hex(pack('e', 8.20234376757474)));

fails correctly.

It seems phpunit converts float numbers using default php float to string conversion which depends on php.ini precision configuration, test case like:

ini_set('precision', '20');
$this->assertSame(8.20234376757473, 8.20234376757474);

fails as expected.

Also, the float diff output has currently limited precision.

To fix exact comparisons & diff output, I propose to convert float numbers to string using function like:

/**
 * Cast float to string with lossless precision.
 */
final public static function castFloatToString(float $value): string
{
    $precisionBackup = ini_get('precision');
    ini_set('precision', '-1');
    try {
        return (string) $value;
    } finally {
        ini_set('precision', $precisionBackup);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature/assertionIssues related to assertions and expectationstype/bugSomething is broken

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions