Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting negative numbers

I was wondering if there is any way to detect if a number is negative in PHP?

I have the following code:

$profitloss = $result->date_sold_price - $result->date_bought_price; 

I need to find out if $profitloss is negative and if it is, I need to echo out that it is.

like image 626
BigJobbies Avatar asked May 26 '11 07:05

BigJobbies


People also ask

Where can negative numbers be found?

Negative numbers are the opposite of positive numbers (+) and are marked on the left side of a number line.

How do you validate negative numbers in Python?

Python Code:n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")

What indicates a negative number?

Negative numbers are symbolized by a minus or a dash (-) sign in front of a number. They are represented on the number line to the left of origin.


2 Answers

if ($profitloss < 0) {    echo "The profitloss is negative"; } 

Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.

In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:

$turnover = 10000; $overheads = 12500;  $difference = abs($turnover-$overheads);  echo "The Difference is ".$difference; 

This would produce The Difference is 2500.

like image 173
Dormouse Avatar answered Oct 24 '22 11:10

Dormouse


I believe this is what you were looking for:

class Expression {     protected $expression;     protected $result;      public function __construct($expression) {         $this->expression = $expression;     }      public function evaluate() {         $this->result = eval("return ".$this->expression.";");         return $this;     }      public function getResult() {         return $this->result;     } }  class NegativeFinder {     protected $expressionObj;      public function __construct(Expression $expressionObj) {         $this->expressionObj = $expressionObj;     }      public function isItNegative() {         $result = $this->expressionObj->evaluate()->getResult();          if($this->hasMinusSign($result)) {             return true;         } else {             return false;         }     }      protected function hasMinusSign($value) {         return (substr(strval($value), 0, 1) == "-");     } } 

Usage:

$soldPrice = 1; $boughtPrice = 2; $negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));  echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :("; 

Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.

:-)

like image 30
Mahn Avatar answered Oct 24 '22 13:10

Mahn