Core\Math::abs
Returns a number without its sign, in the same type as the number you give it.
A negative number becomes positive. A positive number and zero stay the same. An int gives an int, a float gives a float and a decimal gives a decimal, so a price keeps its decimal places.
Use it when only the size of a number matters, not its direction: how far apart two readings are, or how much money is owed, whichever side owes it.
Good to know: the smallest int has no positive int of the same size, so abs throws an ArithmeticError for it. Core\BigInt::abs has no such limit.
Parameters
$nTThe number whose sign is removed: anint, afloator adecimal.
Return value
Returns T. $n without its sign, with the same type as $n. An int gives an int, a uint is returned unchanged, a float gives a float and a decimal gives a decimal with the same decimal places. -0.0 becomes 0.0.
Errors
ArithmeticErrorWhen$nisINT_MIN, whose positive value is one pastINT_MAX.
Examples
A number without its sign
<?nvs// Shows what `Core\Math::abs` returns for an `int`, a `float` and a `decimal`.
// A negative number becomes positive. This prints 42.echo Core\Math::abs(-42), "\n";
// A positive number stays the same. This prints 42.echo Core\Math::abs(42), "\n";
// A `float` gives a `float`. This prints 2.5.echo Core\Math::abs(-2.5), "\n";
// A `decimal` gives a `decimal` and keeps its decimal places. This prints 19.90.decimal $refund = -19.90;echo Core\Math::abs($refund), "\n";42422.519.90How far apart two readings are
<?nvs// Shows how to measure the distance between two numbers. You subtract one from// the other and call `Core\Math::abs` on the result.
float $morning = 14.5;float $evening = 9.0;
// The difference has a sign, so this prints -5.5.echo $evening - $morning, "\n";
// `abs` removes the sign, and what is left is the distance. This prints 5.5.echo Core\Math::abs($evening - $morning), "\n";
// Subtracting the other way round gives the same distance. This prints 5.5.echo Core\Math::abs($morning - $evening), "\n";-5.55.55.5Showing a balance in words
<?nvs// Shows a customer balance on an invoice page. The sign decides the words,// and `Core\Math::abs` gives the amount to show next to them.
class Balance{ // Returns a sentence for a balance. A negative balance means the shop owes the customer. public static function describe(decimal $balance): string { if ($balance < 0) { // `abs` returns a `decimal` here, because the balance is a `decimal`. decimal $owed = Core\Math::abs($balance); return 'We owe you ' . $owed; } if ($balance > 0) { return 'You owe us ' . $balance; } return 'Nothing is due'; }}
// This prints "You owe us 12.50".echo Balance::describe(12.50), "\n";
// This prints "We owe you 3.20". The minus sign is not shown.echo Balance::describe(-3.20), "\n";
// This prints "Nothing is due".echo Balance::describe(0.00), "\n";You owe us 12.50We owe you 3.20Nothing is due