检测负数
我想知道在 PHP 中是否有任何方法可以检测数字是否为负数?
我有以下代码:
$profitloss = $result->date_sold_price - $result->date_bought_price;
我需要找出 $profitloss
是否为负数,如果是,我需要回显它是负数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
编辑:我觉得这对代表来说太简单了,所以这里的内容可能对您也有帮助。
在 PHP 中,我们可以使用
abs()
函数求出整数的绝对值。例如,如果我试图计算两个数字之间的差异,我可以这样做:这将产生
The Difference is 2500
。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:This would produce
The Difference is 2500
.我相信这就是您正在寻找的:
用法:
但是请注意,eval 是一个危险的函数,因此只有当您确实非常需要找出数字是否为负数时才使用它。
:-)
I believe this is what you were looking for:
Usage:
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.
:-)
您可以检查是否
$profitloss < 0
You could check if
$profitloss < 0
不要误会我的意思,但你可以这样做;)
输出:
Don't get me wrong, but you can do this way ;)
Output:
只需将数字乘以 -1 并检查结果是否为正。
Just multiply the number by -1 and check if the result is positive.
您可以使用像这样的三元运算符,使其成为一个衬垫。
You could use a ternary operator like this one, to make it a one liner.
我认为主要思想是查找数字是否为负数并以正确的格式显示它。
对于那些使用 PHP5.3 的人可能有兴趣使用 Number Formatter 类 - http://php .net/manual/en/class.numberformatter.php。此功能以及一系列其他有用的功能可以格式化您的号码。
这里还参考了为什么括号用于负数:
http://www.open.edu /openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
使用三元运算符可以轻松实现。
Can be easily achieved with a ternary operator.
我为 Laravel 项目编写了一个 Helper 函数,但可以在任何地方使用。
I wrote a Helper function for my Laravel project but can be used anywhere.