Changing the sign of a number in PHP?


I have a few floats:


How can I change all these to negative floats so they become:


Also I need a way to do the reverse

If the float is a negative, make it a positive.

2/10/2018 2:42:04 PM

Accepted Answer

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

2/10/2018 2:43:22 PM

$float = -abs($float);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow