Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the sign of a number in PHP?

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.

like image 245
dotty Avatar asked Sep 17 '09 10:09

dotty


People also ask

How do you get the sign of a number?

In common numeral notation (used in arithmetic and elsewhere), the sign of a number is often made explicit by placing a plus or a minus sign before the number. For example, +3 denotes "positive three", and −3 denotes "negative three" (algebraically: the additive inverse of 3).


1 Answers

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

like image 107
drAlberT Avatar answered Sep 21 '22 23:09

drAlberT