How to get sign of a number?
In PHP 7 you should use the combined comparison operator (<=>
):
$sign = $i <=> 0;
A variant to the above in my question I tested and which works as well and has not the floating point problem:
min(1, max(-1, $number))
Edit: The code above has a flaw for float numbers (question was about integer numbers) in the range greater than -1
and smaller than 1
which can be fixed with the following shorty:
min(1, max(-1, $number == 0 ? 0 : $number * INF))
That one still has a flaw for the float NAN
making it return -1
always. That might not be correct. Instead one might want to return 0
as well:
min(1, max(-1, (is_nan($number) or $number == 0) ? 0 : $number * INF))
You can nest ternary operators:
echo $number, ': ', ($number >= 0 ? ($number == 0 ? 0 : 1) : -1 )
This has no problem with floating point precision and avoids an floating point division.
Here's a cool one-liner that will do it for you efficiently and reliably:
function sign($n) {
return ($n > 0) - ($n < 0);
}