Search code examples
phpfloating-pointphp-7zeronegative-number

How can negative zero be tested for in PHP?


In PHP there is a floating point negative zero, which compares identically to floating point positive zero -0.0 === 0.0, despite printing as different strings. There is no integer negative zero in PHP.

I'm writing an extended version of rounding functions and I'm trying to replicate PHP's native behaviour as much as possible. I'm writing it with TDD methodology, so I need a way to verify my code is in line with the native PHP functions by returning negative zero where PHP returns negative zero.

<?php
var_dump(ceil(-0.5));
double(-0)

Is there any way of testing for -0.0 apart from:

  • converting it to a string (string)-0.0 === '-0'
  • serialising it serialize(-0.0) === 'd:-0;'

Solution

  • @njuffa suggested if (1 / $x === -INF), which works but throws a division by zero warning.

    @Manu-sh modified it to do the same thing without the warning by using the new "power of" operator: **

    <?php
    function is_negative_zero($x) {
      return $x ** -1 === -INF;
    }
    
    echo is_negative_zero(0.0)? "Yes": "No";
    echo PHP_EOL;
    
    echo is_negative_zero(-0.0)? "Yes": "No";
    echo PHP_EOL;
    

    Output:

    No
    Yes