Changing the sign of a number in PHP?
PhpMathNumbersSignPhp Problem Overview
I have a few floats:
-4.50
+6.25
-8.00
-1.75
How can I change all these to negative floats so they become:
-4.50
-6.25
-8.00
-1.75
Also I need a way to do the reverse
If the float is a negative, make it a positive.
Php Solutions
Solution 1 - Php
A trivial
$num = $num <= 0 ? $num : -$num ;
or, the better solution, IMHO:
$num = -1 * abs($num)
As @VegardLarsen has posted,
>the explicit multiplication can be avoided for shortness but I prefer readability over shortness
I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.
> "If the float is a negative, make it a positive."
In order to change the sign of a number you can simply do:
$num = 0 - $num;
or, multiply it by -1, of course :)
Solution 2 - Php
$float = -abs($float);
Solution 3 - Php
How about something trivial like:
-
inverting:
$num = -$num;
-
converting only positive into negative:
if ($num > 0) $num = -$num;
-
converting only negative into positive:
if ($num < 0) $num = -$num;
Solution 4 - Php
re the edit: "Also i need a way to do the reverse If the float is a negative, make it a positive"
$number = -$number;
changes the number to its opposite.
Solution 5 - Php
I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:
$int = (($int > 0) ? -$int : $int);
EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:
/* I am not proposing you actually use functions called
"makeNegative" and "makePositive"; I am just presenting
the most direct solution in the form of two clearly named
functions. */
function makeNegative($num) { return -abs($num); }
function makePositive($num) { return abs($num); }
Solution 6 - Php
function positive_number($number)
{
if ($number < 0) {
$number *= -1;
}
return $number;
}
Solution 7 - Php
function invertSign($value)
{
return -$value;
}
Solution 8 - Php
gmp_neg — Negate number
is a PHP function since version 4, that allows you to negate a number, under the GMP PHP API. you can learn more here https://www.php.net/manual/en/ref.gmp.php
<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>
Solution 9 - Php
using alberT and Dan Tao solution:
negative to positive and viceversa
$num = $num <= 0 ? abs($num) : -$num ;