PHP 检查变量是否为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2188675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP check if variable is a whole number
提问by spacemonkey
I have this PHP code:
我有这个 PHP 代码:
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
What i want to know is, how to check whether $entityElementCountis a whole number (2, 6, ...) or partial (2.33, 6.2, ...).
我想知道的是,如何检查$entityElementCount是整数 (2, 6, ...) 还是部分 (2.33, 6.2, ...)。
Thank you!
谢谢!
采纳答案by ghostdog74
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
if (ctype_digit($entityElementCount) ){
// (ctype_digit((string)$entityElementCount)) // as advised.
print "whole number\n";
}else{
print "not whole number\n";
}
回答by Tyler Carter
if (floor($number) == $number)
回答by Joseph
I know this is old, but I thought I'd share something I just found:
我知道这很旧,但我想我会分享我刚刚发现的一些东西:
Use fmodand check for 0
使用fmod并检查是否为 0
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
if (fmod($entityElementCount,1) !== 0.0) {
echo 'Not a whole number!';
} else {
echo 'A whole number!';
}
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 output 0). With fmod, you'll get the fraction portion. For example:
fmod 与 % 不同,因为如果你有一个分数, % 似乎对我不起作用(它返回 0...例如,echo 9.4 % 1;将输出0)。使用 fmod,您将获得分数部分。例如:
echo fmod(9.4, 1);
echo fmod(9.4, 1);
Will output 0.4
会输出 0.4
回答by Martin Vseticka
I would use intvalfunction like this:
我会像这样使用intval函数:
if($number === intval($number)) {
}
Tests:
测试:
var_dump(10 === intval(10)); // prints "bool(true)"
var_dump("10" === intval("10")); // prints "bool(false)"
var_dump(10.5 === intval(10.5)); // prints "bool(false)"
var_dump("0x539" === intval("0x539")); // prints "bool(false)"
Other solutions
其他解决方案
1)
1)
if(floor($number) == $number) { // Currently most upvoted solution:
Tests:
测试:
$number = true;
var_dump(floor($number) == $number); // prints "bool(true)" which is incorrect.
2)
2)
if (is_numeric($number) && floor($number) == $number) {
Corner case:
角落案例:
$number = "0x539";
var_dump(is_numeric($number) && floor($number) == $number); // prints "bool(true)" which depend on context may or may not be what you want
3)
3)
if (ctype_digit($number)) {
Tests:
测试:
var_dump(ctype_digit("0x539")); // prints "bool(false)"
var_dump(ctype_digit(10)); // prints "bool(false)"
var_dump(ctype_digit(0x53)); // prints "bool(false)"
回答by Aistina
The basic way, as Chacha said is
正如 Chacha 所说,基本方法是
if (floor($number) == $number)
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 enoughto 1 to be considered a whole number. Therefore try something like this:
但是,浮点类型无法准确存储数字,这意味着 1 可能存储为 0.999999997。这当然意味着上述检查将失败,因为它会被四舍五入为 0,即使出于您的目的,它已经足够接近1 以被视为一个整数。因此尝试这样的事情:
if (abs($number - round($number)) < 0.0001)
回答by Anthony
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 use is_int():
如果您知道它将是数字(意味着它永远不会将整数转换为字符串,例如"ten"or "100",您可以使用is_int():
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
$entityWholeNumber = is_int($entityElementCount);
echo ($entityWholeNumber) ? "Whole Number!" : "Not a whole number!";
回答by Antonio Vinicius Menezes Medei
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 $valueis a number using is_numeric($value)reduces the number of failures for many solutions, but does not turn any solution into an ultimate one:
我测试了所有提出的解决方案,其中提到了许多有问题的值,它们至少在一个测试用例中都失败了。开始检查是否$value是一个数字,使用is_numeric($value)可以减少许多解决方案的失败次数,但不会将任何解决方案转化为最终解决方案:
$test_cases = array(0.29, 2, 6, 2.33, 6.2, '10.00', 1.4, 10, "10", 10.5, "0x539", true,
false, 0x53, 9.4, "ten", "100", 1, 0.999999997, 0, 0.0001, 1.0, 0.9999999,
(-(4.42-5))/0.29);
function is_whole_number($value) {
// Doing this prevents failing for values like true or "ten"
if (!is_numeric($value)) {
return false;
}
// @ghostdog74's solution fails for "10.00"
// return (ctype_digit((string) $value));
// Both @Maurice's solutions fails for "10.00"
// return ((string) $value === (string) (int) $value);
// return is_int($value);
// @j.hull's solution always returns true for numeric values
// return (abs($value) % 1 == 0 ? true : false);
// @ MartyIX's solution fails for "10.00"
// return ($value === intval($value));
// This one fails for (-(4.42-5))/0.29
// return (floor($value) == $value);
// This one fails for 2
// return ctype_digit($value);
// I didn't understand Josh Crozier's answer
// @joseph4tw's solution fails for (-(4.42-5))/0.29
// return !(fmod($value, 1) != 0);
// If you are unsure about the double negation, doing this way produces the same
// results:
// return (fmod($value, 1) == 0);
// Doing this way, it always returns false
// return (fmod($value, 1) === 0);
// @Anthony's solution fails for "10.00"
// return (is_numeric($value) && is_int($value));
// @Aistina's solution fails for 0.999999997
// return (abs($value - round($value)) < 0.0001);
// @Notinlist's solution fails for 0.999999997
// return (round($value, 3) == round($value));
}
foreach ($test_cases as $test_case) {
var_dump($test_case);
echo ' is a whole number? ';
echo is_whole_number($test_case) ? 'yes' : 'no';
echo "\n";
}
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.
我认为像@Aistina 和@Notinlist 提出的解决方案是最好的解决方案,因为它们使用错误阈值来确定值是否为整数。重要的是要注意,它们对表达式按预期工作(-(4.42-5))/0.29,而所有其他人在该测试用例中都失败了。
I decided to use @Notinlist's solution because of its readability:
我决定使用@Notinlist 的解决方案,因为它的可读性:
function is_whole_number($value) {
return (is_numeric($value) && (round($value, 3) == round($value)));
}
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.
我需要测试值是整数、货币还是百分比,我认为 2 位精度就足够了,所以 @Notinlist 的解决方案符合我的需要。
Running this test:
运行此测试:
$test_cases = array(0.29, 2, 6, 2.33, 6.2, '10.00', 1.4, 10, "10", 10.5, "0x539", true,
false, 0x53, 9.4, "ten", "100", 1, 0.999999997, 0, 0.0001, 1.0, 0.9999999,
(-(4.42-5))/0.29);
function is_whole_number($value) {
return (is_numeric($value) && (round($value, 3) == round($value)));
}
foreach ($test_cases as $test_case) {
var_dump($test_case);
echo ' is a whole number? ';
echo is_whole_number($test_case) ? 'yes' : 'no';
echo "\n";
}
Produces the following output:
产生以下输出:
float(0.29)
is a whole number? no
int(2)
is a whole number? yes
int(6)
is a whole number? yes
float(2.33)
is a whole number? no
float(6.2)
is a whole number? no
string(5) "10.00"
is a whole number? yes
float(1.4)
is a whole number? no
int(10)
is a whole number? yes
string(2) "10"
is a whole number? yes
float(10.5)
is a whole number? no
string(5) "0x539"
is a whole number? yes
bool(true)
is a whole number? no
bool(false)
is a whole number? no
int(83)
is a whole number? yes
float(9.4)
is a whole number? no
string(3) "ten"
is a whole number? no
string(3) "100"
is a whole number? yes
int(1)
is a whole number? yes
float(0.999999997)
is a whole number? yes
int(0)
is a whole number? yes
float(0.0001)
is a whole number? yes
float(1)
is a whole number? yes
float(0.9999999)
is a whole number? yes
float(2)
is a whole number? yes
回答by Notinlist
if(floor($number) == $number)
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.
不是一个稳定的算法。当一个值在数学上为 1.0 时,数值可以是 0.9999999。如果你在它上面应用 floor() 它将是 0,它不等于 0.9999999。
You have to guess a precision radius for example 3 digits
您必须猜测精度半径,例如 3 位数
if(round($number,3) == round($number))
回答by Artron
(string)floor($pecahformat[3])!=(string)$pecahformat[3]
回答by BKY
$num = 2.0000000000001;
if( $num == floor( $num ) ){
echo('whole');
}else{
echo('fraction');
}
EX:
前任:
2.0000000000001 | fraction
2.0000000000001 | 分数
2.1 | fraction
2.1 | 分数
2.00 | whole
2.00 | 所有的
2 | whole
2 | 所有的

