PHPで数値が負かどうかを検出する方法があるかどうか疑問に思っていましたか?
次のコードがあります。
$profitloss = $result->date_sold_price - $result->date_bought_price;
が否定的かどうかを調べる必要があり、$profitloss
否定的である場合は、否定的であることをエコーする必要があります。
PHPで数値が負かどうかを検出する方法があるかどうか疑問に思っていましたか?
次のコードがあります。
$profitloss = $result->date_sold_price - $result->date_bought_price;
が否定的かどうかを調べる必要があり、$profitloss
否定的である場合は、否定的であることをエコーする必要があります。
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
編集:これは担当者にとって単純すぎる答えだと思うので、ここでも役立つと思われるものがあります。
PHPでは、関数を使用して整数の絶対値を見つけることができますabs()
。たとえば、2つの図の違いを理解しようとすると、次のようになります。
$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) == "-")
あなたは$profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "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)
括弧が負の数に使用される理由についての参照もここにあり ます。