PHP 检查变量是否为整数
我有这个 PHP 代码:
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
我想知道的是,如何检查 $entityElementCount 是整数 (2, 6, ...) 还是部分数 (2.33, 6.2, ...) 。
谢谢你!
I have this PHP code:
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
What i want to know is, how to check whether $entityElementCount is a whole number (2, 6, ...) or partial (2.33, 6.2, ...).
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(22)
我知道这已经很旧了,但我想我应该分享一些我刚刚发现的东西:
使用 fmod< /a> 并检查 0
fmod 与 % 不同,因为如果你有一个分数,% 似乎对我不起作用(它返回 0...例如,
echo 9.4 % 1;
将输出0
)。使用 fmod,您将得到分数部分。例如:echo fmod(9.4, 1);
将输出
0.4
I know this is old, but I thought I'd share something I just found:
Use fmod and check for 0
fmod is different from % because if you have a fraction, % doesn't seem to work for me (it returns 0...for example,
echo 9.4 % 1;
will output0
). With fmod, you'll get the fraction portion. For example:echo fmod(9.4, 1);
Will output
0.4
我会使用 intval 函数,如下所示:
测试:
其他解决方案
1)
测试:
2)
极端情况:
3)
测试:
I would use intval function like this:
Tests:
Other solutions
1)
Tests:
2)
Corner case:
3)
Tests:
基本方式,正如 Chacha 所说,
但是,浮点类型无法准确存储数字,这意味着 1 可能会存储为 0.999999997。这当然意味着上面的检查将失败,因为它将向下舍入为 0,即使对于您的目的来说,它足够接近到 1 以被视为整数。因此尝试这样的事情:
The basic way, as Chacha said is
However, floating point types cannot accurately store numbers, which means that 1 might be stored as 0.999999997. This will of course mean the above check will fail, because it will be rounded down to 0, even though for your purposes it is close enough to 1 to be considered a whole number. Therefore try something like this:
我测试了所有提出的解决方案,其中提到了许多有问题的值,它们至少在一个测试用例中都失败了。使用
is_numeric($value)
开始检查 $value 是否是一个数字,可以减少许多解决方案的失败次数,但不会将任何解决方案变成最终解决方案:我认为@Aistina 和 @Notinlist 提出的解决方案是最好的解决方案,因为它们使用错误阈值来确定值是否是整数。值得注意的是,它们对于表达式
(-(4.42-5))/0.29
的工作符合预期,而所有其他在该测试用例中都失败了。我决定使用@Notinlist的解决方案,因为它的可读性:
我需要测试值是否是整数、货币或百分比,我认为2位数字的精度就足够了,所以@Notinlist的解决方案符合我的需求。
运行此测试:
产生以下输出:
I tested all the proposed solutions with many problematic values mentioned, they all fail for at least one of the test cases. Start checking if
$value
is a number usingis_numeric($value)
reduces the number of failures for many solutions, but does not turn any solution into an ultimate one:I think that solutions like the ones proposed by @Aistina and @Notinlist are the best ones, because they use an error threshold to decide whether a value is a whole number. It is important to note that they worked as expected for the expression
(-(4.42-5))/0.29
, while all the others failed in that test case.I decided to use @Notinlist's solution because of its readability:
I need to test if values are whole numbers, currency or percentage, I think 2 digits of precision is enough, so @Notinlist's solution fits my needs.
Running this test:
Produces the following output:
如果您知道它将是数字(意味着它永远不会是转换为字符串的整数,例如
"ten"
或"100"
,您可以使用 is_int() :If you know that it will be numeric (meaning it won't ever be a an integer cast as a string, like
"ten"
or"100"
, you can just useis_int()
:不是一个稳定的算法。当某个值在数学上为 1.0 时,该数值可以是 0.9999999。如果对它应用Floor(),它将是0,不等于0.9999999。
您必须猜测精确半径,例如 3 位数字
Is not a stable algorithm. When a value is matematically 1.0 the numerical value can be 0.9999999. If you apply floor() on it it will be 0 which is not equals to 0.9999999.
You have to guess a precision radius for example 3 digits
例如:
2.0000000000001 |分数
2.1 |分数
2.00 |整个
2 |所有的
EX:
2.0000000000001 | fraction
2.1 | fraction
2.00 | whole
2 | whole
我想出的另一种黑客方法是
ceil($value) === Floor($value)
。如果数字是整数,则这应该始终为真,即使将 10 与 10.000 进行比较,甚至可以处理字符串中的数字,例如ceil("10.0") === Floor(10).
Another hacky way I came up with is
ceil($value) === floor($value)
. If a number is a whole number, this should always be true, even if comparing 10 with 10.000 and will even work with numbers cast in string, for exampleceil("10.0") === floor(10)
.@Tyler Carter 解决方案的改进版本,它比原始解决方案更好地处理边缘情况:
(Tyler 的代码无法识别字符串“123foobar”不是整数。这个改进版本不会犯这个错误。归功于@Shafizadeh发现错误的注释也是 php7
strict_types=1
兼容的)improved version of @Tyler Carter's solution, which handles edge cases better than the original:
(Tyler's code fail to recognize that the string "123foobar" is not a whole number. this improved version won't make that mistake. credits to @Shafizadeh in the comments for discovering the bug. also this is php7
strict_types=1
-compatible)如果这是一个整数,则为真
This will be true if this is a whole number
这并不是试图回答这个问题。他们已经有很多答案了。如果您按照问题所暗示的那样进行统计,我怀疑@antonio-vinicius-menezes-medei 的答案最适合您。但是我需要这个答案来进行输入验证。我发现此检查对于验证输入字符串是否为整数更可靠:
is_numeric($number) && preg_match('/^[0-9]+$/', $number)
'is_numeric' 只是纠正 preg_match 中“true”转换为“1”的情况。
所以就用@antonio-vinicius-menezes-medei 的回答。我写了一个脚本来测试下面的内容。请注意
ini_set(' precision', 20)
。 preg_match 会将参数转换为字符串。如果您的精度设置为低于浮点值的长度,它们将简单地按给定的精度舍入。与 @antonio-vinicius-menezes-medei 答案类似,此精度设置将强制类似的估计长度。产生以下输出:
float(0.28999999999999998002) 否
int(2) 是
int(6) 是
浮点(2.3300000000000000711) 否
浮点(6.2000000000000001776) 否
字符串(5) "10.00" 否
浮点数(1.39999999999999999112) 否
int(10) 是
字符串(2) "10" 是
浮动(10.5) 否
字符串(5)“0x539”否
bool(true) 否
bool(false) 否
int(83) 是
浮点(9.4000000000000003553) 否
string(3) "十" 否
字符串(3)“100”是
int(1) 是
浮点(0.99999999699999997382) 否
int(0) 是
浮点(0.00010000000000000000479) 否
浮点(1) 是
浮点数(0.99999990000000005264) 否
浮点(2.0000000000000004441) 否
This is not an attempt to answer this question so much. Their are plenty of answer already. If you are doing statistics as the question implies I suspect @antonio-vinicius-menezes-medei answer will suite you best. However I needed this answer for input validation. I found this check more reliable for validating an input string is a whole number:
is_numeric($number) && preg_match('/^[0-9]+$/', $number)
The 'is_numeric' simply corrects for "true" converting to "1" in preg_match.
So playing off of @antonio-vinicius-menezes-medei answer. I wrote a script to test this below. Note the
ini_set('precision', 20)
. preg_match will convert the argument to a string. If your precicion is set below the length of the float values they will simply round at the given precision. Similar to @antonio-vinicius-menezes-medei answer this precision setting will force a similar estimation length.Which produces this output:
float(0.28999999999999998002) No
int(2) Yes
int(6) Yes
float(2.3300000000000000711) No
float(6.2000000000000001776) No
string(5) "10.00" No
float(1.3999999999999999112) No
int(10) Yes
string(2) "10" Yes
float(10.5) No
string(5) "0x539" No
bool(true) No
bool(false) No
int(83) Yes
float(9.4000000000000003553) No
string(3) "ten" No
string(3) "100" Yes
int(1) Yes
float(0.99999999699999997382) No
int(0) Yes
float(0.00010000000000000000479) No
float(1) Yes
float(0.99999990000000005264) No
float(2.0000000000000004441) No
只是为了与本地化字符串/数字分享我的解决方案,这个组合对我来说就像一个魅力。
Just to share my solution with localized string/number, this combo worked like a charm for me.
试试这个
Try this
看似简单的方法是使用模数 (%) 来确定值是否为整数。
如果 y 是整数以外的值,则结果不是零 (0)。那么测试将是:
假设这会将负数视为整数,然后将 ABS() 包裹在 y 周围以始终测试正数。
What seems a simple approach would be to use modulus (%) to determine if a value is whole or not.
if y is anything other then a whole number the result is not a zero (0). A test then would be:
Granted this will view a negative number as a whole number, then then just wrap ABS() around
y
to always test on the positive.我总是使用类型转换来检查变量是否包含整数,当您不知道值的来源或类型时,这很方便。
在您的特定情况下,我会使用 is_int()
I always use typecasting to check if variables contain a whole number, handy when you don't know the origin or type of the value.
In your particular case, I would use is_int()
仅适用于正整数的简单解决方案。这可能并不适用于所有情况。
如果需要,您可以使用 Floor() 而不是 ceil()。
A simple solution for positive whole numbers only. This may not work for everything.
You can use floor() instead of ceil() if so desired.
如果您想检查整数和小数,可以执行以下操作:
这将正确检查您的数字,而无需四舍五入、将其转换为 int (在小数的情况下将丢失小数部分)或执行 以下操作:任何数学。但是,如果您想将
1.00
视为整数,那么那就完全是另一回事了。If you want to check for both whole and decimal numbers, you can do the following:
This will correctly check your number without rounding it, casting it to int (which in the case of a decimal number will lose the decimal part), or doing any math. If, however, you want to treat
1.00
as a whole number, then that's a whole another story.我知道这是一篇非常旧的帖子,但这是一个简单的函数,它将返回一个有效的整数并将其转换为 int。如果失败则返回 false。
用法 :
I know this is a super old post but this is a simple function that will return a valid whole number and cast it to an int. Returns false if it fails.
Usage :