Changing the sign of a number in PHP?

前端 未结 8 1353
星月不相逢
星月不相逢 2021-01-31 13:26

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         


        
相关标签:
8条回答
  • 2021-01-31 13:47
    $float = -abs($float);
    
    0 讨论(0)
  • 2021-01-31 13:47
    function invertSign($value)
    {
        return -$value;
    }
    
    0 讨论(0)
  • 2021-01-31 13:50

    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.

    0 讨论(0)
  • 2021-01-31 13:52

    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;
      
    0 讨论(0)
  • 2021-01-31 13:59

    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 :)

    0 讨论(0)
  • 2021-01-31 13:59
    function positive_number($number)
    {
        if ($number < 0) {
            $number *= -1;
        }
    
       return $number;
    }
    
    0 讨论(0)
提交回复
热议问题