Big*_*ies 53 php comparison-operators
我想知道是否还有检测PHP中的数字是否为负数?
我有以下代码
$profitloss = $result->date_sold_price - $result->date_bought_price;
Run Code Online (Sandbox Code Playgroud)
我需要找出$ profitloss是否是负面的...如果是我需要回应它是的.
Mah*_*ahn 176
我相信这就是你要找的东西:
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) == "-");
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Run Code Online (Sandbox Code Playgroud)
但请注意,eval是一个危险的函数,因此只有当你确实需要找出一个数字是负数时才使用它.
:-)
Dor*_*use 156
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Run Code Online (Sandbox Code Playgroud)
编辑:我觉得这对于代表来说太简单了,所以这里有一些你可能会觉得有帮助的东西.
在PHP中,我们可以通过使用abs()函数找到整数的绝对值.例如,如果我试图解决两个数字之间的差异,我可以这样做:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
Run Code Online (Sandbox Code Playgroud)
这会产生The Difference is 2500.
Mar*_*rty 19
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
Run Code Online (Sandbox Code Playgroud)
你可以检查一下 $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
Run Code Online (Sandbox Code Playgroud)
不要误会我的意思,但你可以这样做;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Run Code Online (Sandbox Code Playgroud)