Few ways to convert values to negative
<?php
// Multiplying by "-1"
$v = -1 * abs($v);
// Using ternary operator
$v = $v <= 0 ? $v : -$v;
?>
(PHP 4, PHP 5, PHP 7)
abs — Absolute value
number
The numeric value to process
The absolute value of number
. If the
argument number
is
of type float, the return type is also float,
otherwise it is integer (as float usually has a
bigger value range than integer).
Example #1 abs() example
<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5); // 5 (integer)
echo abs(-5); // 5 (integer)
?>
Few ways to convert values to negative
<?php
// Multiplying by "-1"
$v = -1 * abs($v);
// Using ternary operator
$v = $v <= 0 ? $v : -$v;
?>
[*EDIT* by danbrown AT php DOT net: Merged user's corrected code with previous post content.]
jeremys indicated one thing - there is no sgn function wich actually seems a bit strange for me. Of course it is as simple as possible, but it is usefull and it is a standard math function needed occasionally.
Well, I have solved this function in a bit different matter:
<?php
function sgn($liczba)
{
if($liczba>0)
$liczba=1;
else if($liczba<0)
$liczba=-1;
else if(!is_numeric($liczba))
$liczba=null;
else
$liczba=0;
return $liczba;
}
?>
The difference is that it returns null when the argument isn't a number at all.
If you don't have/want GMP and are working with large numbers/currencies:
<?php
function mb_abs($number)
{
return str_replace('-','',$number);
}
?>
No need to worry about encoding, as your numbers should all be basic (ANSI) strings.