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;'
3
Answers
@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:
**
Output:
This work only for literals but not for variables:
But this seems to work also for variables:
You can check by yourself that this follow the mathematics rules,
here are the Wolframalpha results for -0.0 ** -1 and 0.0 ** -1
Floating point numbers have a specific bit that is set in the internal coding if it is negative. This test is also suitable to distinguish between +0.0 and -0.0. The test is also independent of how PHP performs operations with -0.0 and +0.0.
Examples:
Special test for negative float zero:
Examples: