Core\Math::sign
Core\Math::sign checks whether a number is below zero, zero, or above zero. It returns -1, 0 or 1.
It works with int, float and decimal values, and the result is always an int. -0.0 is zero, so the result for it is 0. The infinities are not zero: -Core\Math::INFINITY gives -1.
NaN (a value that means "not a number") is not below, above or equal to zero. For NaN, Core\Math::sign throws a RuntimeError. A uint bigger than Core\Math::INT_MAX throws an ArithmeticError.
The examples below show the three results for each type of number, then zero and NaN, then a report that says whether sales went up or down.
Parameters
$nint|float|decimalThe number to check: anint, afloator adecimal.
Return value
Returns int. -1, 0 or 1, as an int. -0.0 is zero, so the result for it is 0.
Errors
RuntimeErrorWhen$nisNaN(a value that means "not a number").NaNis not below, above or equal to zero.ArithmeticErrorWhen$nis auintbigger thanCore\Math::INT_MAX.
Examples
Three results
<?nvs// Shows the three results of `Core\Math::sign` for each type of number.
// A whole number. This prints -1, 0 and 1.echo Core\Math::sign(-42), ' ', Core\Math::sign(0), ' ', Core\Math::sign(7), "\n";
// A `float`. This prints -1, 0 and 1.echo Core\Math::sign(-0.25), ' ', Core\Math::sign(0.0), ' ', Core\Math::sign(3.5), "\n";
// A `decimal`, such as an amount of money. This prints -1, 0 and 1.decimal $refund = -19.90;decimal $nothing = 0.00;decimal $payment = 5.00;echo Core\Math::sign($refund), ' ', Core\Math::sign($nothing), ' ', Core\Math::sign($payment), "\n";-1 0 1-1 0 1-1 0 1Zero and nan
<?nvs// Shows the result for negative zero and the infinities, and what happens for `NaN`.
// `-0.0` is zero. This prints 0.echo Core\Math::sign(-0.0), "\n";
// The infinities are below and above zero. This prints -1, then 1.echo Core\Math::sign(-Core\Math::INFINITY), "\n";echo Core\Math::sign(Core\Math::INFINITY), "\n";
// `NaN` means "not a number". It is not below, above or equal to zero,// so this throws a `RuntimeError`.try { echo Core\Math::sign(Core\Math::NAN), "\n";} catch (RuntimeError $error) { echo "NaN has no sign.\n";}0-11NaN has no sign.Sales up or down
<?nvs// Shows how a sales report says whether each month was better or worse than the month before.
class Report{ // Returns "down", "same" or "up". The sign is -1, 0 or 1, so adding 1 picks a word. public static function trend(int $before, int $now): string { array<string> $words = ['down', 'same', 'up']; return $words[Core\Math::sign($now - $before) + 1]; }}
// This prints "up", then "same", then "down".array<int> $sales = [1200, 1450, 1450, 980];int $month = 1;while ($month < 4) { echo 'Month ', $month + 1, ': ', Report::trend($sales[$month - 1], $sales[$month]), "\n"; $month = $month + 1;}Month 2: upMonth 3: sameMonth 4: down