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.
Negative numbers are the opposite of positive numbers (+) and are marked on the left side of a number line.
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. ")
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With