检测负数

| 我想知道是否有任何方法可以检测PHP中的数字是否为负数? 我有以下代码:
$profitloss = $result->date_sold_price - $result->date_bought_price;
我需要确定
$profitloss
是否为负,如果为负,则需要回显它为负。     
已邀请:
if ($profitloss < 0)
{
   echo \"The profitloss is negative\";
}
编辑:我觉得这对销售代表来说太简单了,所以这对您可能也会有所帮助。 在PHP中,我们可以使用
abs()
函数来找到整数的绝对值。例如,如果我试图找出两个数字之间的差异,我可以这样做:
$turnover = 10000;
$overheads = 12500;

$difference = abs($turnover-$overheads);

echo \"The Difference is \".$difference;
这将产生
The Difference is 2500
。     
我相信这就是您想要的:
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) == \"-\");
    }
}
用法:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression(\"$soldPrice - $boughtPrice\"));

echo ($negativeFinderObj->isItNegative()) ? \"It is negative!\" : \"It is not negative :(\";
但是请注意eval是一个危险函数,因此仅在确实需要确定数字是否为负数时才使用它。 :-)     
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == \"-\")
    
您可以检查ѭ​​9ѭ
if ($profitloss < 0):
    echo \"Less than 0\\n\";
endif;
    
if ( $profitloss < 0 ) {
   echo \"negative\";
};
    
只需将数字乘以-1,然后检查结果是否为正。     
别误会我,但是您可以这样做;)
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>\';
}
    }
}
输出:
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!
    
您可以使用像这样的三元运算符,使其成为一个直线。
echo ($profitloss < 0) ? \'false\' : \'true\';
    
我认为主要思想是查找数字是否为负数并以正确的格式显示它。 对于那些使用PHP5.3的人,可能对使用数字格式化程序类感兴趣-http://php.net/manual/en/class.numberformatter.php。此功能以及其他有用的功能可以格式化您的电话号码。
$profitLoss = 25000 - 55000;

$a= new \\NumberFormatter(\"en-UK\", \\NumberFormatter::CURRENCY); 
$a->formatCurrency($profitLoss, \'EUR\');
// would display (€30,000.00)
这也是为什么括号用于负数的参考: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7     

要回复问题请先登录注册