Detecting negative numbers Detecting negative numbers php php

Detecting negative numbers


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.


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.

:-)


if(x < 0)if(abs(x) != x)if(substr(strval(x), 0, 1) == "-")