Changing the sign of a number in PHP?

前端 未结 8 1344
星月不相逢
星月不相逢 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 14:06

    using alberT and Dan Tao solution:

    negative to positive and viceversa

    $num = $num <= 0 ? abs($num) : -$num ;
    
    0 讨论(0)
  • 2021-01-31 14:09

    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); }
    
    0 讨论(0)
提交回复
热议问题