-0 is not equal to 0

I have a function that calculates a value that is a float:

function crunch (float $a, float $b):float
{
  //do stuff
  return $result;
}

function testSomething (float $a, float $b):bool
{
  //if $result is -0 that returns false
  $result = crunch($a, $b);
  return $result === 0;
}

Why is -0 not equal to 0 and how can one safely check if this number is equal if it 0should be the same as -0?

UPDATE

Since the question arose, for more details. I have a class Vec2that has x()both y()getters and a method called crossthat looks like this:

public function cross(Vec2 $vec2):float
{
  return ($this->_x * $vec2->_y) - ($vec2->_x * $this->_y);
}

Running this code:

$cross = $this->cross($d);

causes the debugger output

enter image description here

and $cross === 0is rated as false;

+4
source share
3 answers

Move 0 to float. This is probably not the case, because 0 as the literal is int, and the result is float, therefore === false due to types.

, - , , ( ):

php -r '$a = (float) -0; $b = 0; echo ($a === $b);'

:

php -r '$a = (float) -0; $b = (float) 0; echo ($a == $b);'
+5
  • - . .
  • , , , .

:

function float_equiv(float $a, float $b, float $epsilon=NULL) {
    // default to PHP configured display precision
    $epsilon = $epsilon ?: pow(10, -1*ini_get('precision'));

    if( abs($a - $b) < $epsilon ) {
        return true;
    }
    return false;
}
+4

@monstercode

- . , -0 = 0, (, ) - , float.

.

$result_1 = 1234*0;// remains an integer
$result_2 = -1234*0;// remains an integer

$result_3 = -1.234*0;// becomes a float
$result_4 = 1.234*0; // becomes a float

var_dump($result_1 === 0); // true
var_dump($result_2 === 0); // true

var_dump($result_3 === 0); // false
var_dump($result_4 === 0); // false
0

Source: https://habr.com/ru/post/1694660/


All Articles