PHP检查变量是否为整数

问题描述 投票:28回答:18

我有这个PHP代码:

$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;

我想知道的是,如何检查$ entityElementCount是一个整数(2,6,...)还是部分(2.33,6.2,...)。

谢谢!

php integer double numbers
18个回答
18
投票
$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";
}

1
投票
floor($entityElementCount) == $entityElementCount

如果这是一个整数,那将是真的


1
投票

这不是试图如此回答这个问题。他们已经有了很多答案。如果您正在进行统计,问题意味着我怀疑@ 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类似,此精度设置将强制使用类似的估计长度。

  ini_set('precision', 20);
  $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);

  foreach ($test_cases as $number)
  {
    echo '<strong>';
    var_dump($number);
    echo '</strong>';
    echo boolFormater(is_numeric($number) && preg_match('/^[0-9]+$/', $number));
    echo '<br>';
  }

  function boolFormater($value)
  {
    if ($value)
    {
      return 'Yes';
    }
    return 'No';
  }

哪个产生这个输出:

漂浮(0.28999999999999998002)没有 int(2)是的 int(6)是的 float(2.3300000000000000711)没有 浮动(6.2000000000000001776)没有 string(5)“10.00”没有 漂浮(1.3999999999999999112)没有 int(10)是的 string(2)“10”是的 漂浮(10.5)没有 string(5)“0x539”没有 布尔(真)没有 布尔(假)没有 int(83)是的 float(9.4000000000000003553)没有 string(3)“ten”No string(3)“100”是的 int(1)是的 float(0.99999999699999997382)没有 int(0)是的 float(0.00010000000000000000479)没有 float(1)是的 float(0.99999990000000005264)没有 float(2.0000000000000004441)没有


1
投票

@Tyler Carter解决方案的改进版本,可以比原始版本更好地处理边缘情况:

function is_whole_number($number){
    return (is_float(($f=filter_var($number,FILTER_VALIDATE_FLOAT))) && floor($f)===$f);    
}

(Tyler的代码没有认识到字符串“123foobar”不是一个完整的数字。这个改进的版本不会犯这个错误。在发现bug的评论中归功于@Shafizadeh。这也是php7 strict_types=1兼容的)


0
投票

看似简单的方法是使用模数(%)来确定值是否为完整值。

x = y % 1  

如果y是除了整数之外的任何其他结果,则结果不是零(0)。那么测试将是:

if (y % 1 == 0) { 
   // this is a whole number  
} else { 
   // this is not a whole number 
}

var isWhole = (y % 1 == 0? true: false);  // to get a boolean return. 

当然,这将查看负数作为整数,然后只需在y周围包裹ABS()以始终测试正数。


0
投票

我总是使用类型转换来检查变量是否包含整数,当您不知道值的来源或类型时,方便。

if ((string) $var === (string) (int) $var) {
    echo 'whole number';
} else {
    echo 'whatever it is, it\'s something else';
}

在你的特殊情况下,我会使用is_int()

if (is_int($var) {
    echo 'integer';
}

0
投票

仅对正整数的简单解决方案。这可能不适用于所有事情。

$string = '0x539';
$ceil = ceil($string);

if($ceil < 1){
  $ceil = FALSE; // or whatever you want i.e 0 or 1
}

echo $ceil; // 1337

如果需要,您可以使用floor()而不是ceil()。


0
投票
function isInteger($value)
{
    // '1' + 0 == int, '1.2' + 0 == float, '1e2' == float
    return is_numeric($value) && is_int($value + 0);
}

function isWholeNumber($value)
{
    return is_numeric($value)
        && (is_int($value + 0)
            || (intval($value + 0) === intval(ceil($value + 0))));
}

如果要检查整数和十进制数,可以执行以下操作:

if (isInteger($foo))
{
    // integer as int or string
}
if (isWholeNumber($foo))
{
    // integer as int or string, or float/double with zero decimal part
}
else if (is_numeric($foo))
{
    // decimal number - still numeric, but not int
}

这将正确检查您的数字而不对其进行舍入,将其转换为int(在十进制数字的情况下将丢失小数部分),或进行任何数学运算。但是,如果你想将1.00视为一个整数,那么这就是另一个故事。


0
投票

我知道这是一个超级老帖子,但这是一个简单的函数,它将返回一个有效的整数并将其转换为int。如果失败则返回false。

function isWholeNumber($v)
{
    if ($v !='' && is_numeric($v) && strpos($v, '.') === false) {
        return (int)$v;
    }
    return false;
}

用法:

$a = 43;
$b = 4.3;
$c = 'four_three';

isWholeNumber($a) // 43
isWholeNumber($b) // false
isWholeNumber($c) // false

0
投票

只是为了与本地化的字符串/数字分享我的解决方案,这个组合对我来说就像一个魅力。

public static function isWholeNumber ($input, $decimalDelimiter = ',')
{
    if (is_string($input)){
        $input = str_replace($decimalDelimiter, '.', $input);
        $input = floatval($input);
    }

    if (fmod($input,1) !== 0.0) {
        return false;
    }

    return true;
}

0
投票
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;

Method 1-
    By using ctype_digit() function. 

    if ( ctype_digit($entityElementCount )) { 
        echo "Whole Number\n"; 
    } else { 
        echo "Not a whole Number\n"; 
    } 


Method 2-
    By using is_float() function. 

    if (is_float($entityElementCount )) { 
        echo "Not a Whole Number\n"; 
    } else { 
        echo "Whole Number\n"; 
    } 


Method 3-
    By using is_int() function. 

    if (is_int($entityElementCount )) { 
        echo "Whole Number\n"; 
    } else { 
        echo "Not a whole Number\n"; 
    } 


Method 5-
    By using fmod() function. 

    It needs 2 parameters one dividend and other is divisor
    Here $dividend=$entityElementCount and divisor=1
    if (fmod($dividend,$divisor) !== 0.0) {
        echo 'Not a whole number!';
    } else {
     echo 'A whole number!';
    }

there are some more function like intval(), floor(),... can be used to check it`enter code here`

42
投票
if (floor($number) == $number)

39
投票

我知道这是旧的,但我想我会分享一些我刚发现的东西:

使用fmod并检查0

$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
if (fmod($entityElementCount,1) !== 0.0) {
    echo 'Not a whole number!';
} else {
    echo 'A whole number!';
}

fmod与%不同,因为如果你有一个分数,%似乎对我不起作用(它返回0 ...例如,echo 9.4 % 1;将输出0)。使用fmod,你将获得分数部分。例如:

echo fmod(9.4, 1);

将输出0.4


10
投票

我会像这样使用intval函数:

if($number === intval($number)) {

}

测试:

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)"

其他方案

1)

if(floor($number) == $number) {   // Currently most upvoted solution: 

测试:

$number = true;
var_dump(floor($number) == $number); // prints "bool(true)" which is incorrect.

2)

if (is_numeric($number) && floor($number) == $number) {

转角案例:

$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)

if (ctype_digit($number)) {

测试:

var_dump(ctype_digit("0x539")); // prints "bool(false)"
var_dump(ctype_digit(10)); // prints "bool(false)"
var_dump(ctype_digit(0x53)); // prints "bool(false)"

9
投票

Chacha说的基本方法是

if (floor($number) == $number)

但是,浮点类型无法准确存储数字,这意味着1可能存储为0.999999997。这当然意味着上述检查将失败,因为它将向下舍入为0,即使为了您的目的,它足够接近1被视为整数。因此尝试这样的事情:

if (abs($number - round($number)) < 0.0001)

6
投票

如果你知道它将是数字(意味着它永远不会是一个字符串整数,如"ten""100",你可以使用is_int()

$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
$entityWholeNumber = is_int($entityElementCount);

echo ($entityWholeNumber) ? "Whole Number!" : "Not a whole number!";

4
投票

我测试了所有提出的解决方案,提到了许多有问题的值,它们都至少在一个测试用例中失败了。开始检查$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";
}

我认为@Aistina和@Notinlist提出的解决方案是最好的解决方案,因为它们使用错误阈值来确定值是否为整数。值得注意的是,它们在表达(-(4.42-5))/0.29的过程中按预期工作,而其他所有其他测试用例都失败了。

我决定使用@Notinlist的解决方案,因为它具有可读性:

function is_whole_number($value) {
    return (is_numeric($value) && (round($value, 3) == round($value)));
}

我需要测试值是整数,货币还是百分比,我认为2位精度就足够了,所以@Notinlist的解决方案符合我的需求。

运行此测试:

$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";
}

产生以下输出:

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

3
投票
if(floor($number) == $number)

不是一个稳定的算法。当值为1.0时,数值可以是0.9999999。如果对它应用floor(),它将为0,不等于0.9999999。

您必须猜测精度半径,例如3位数

if(round($number,3) == round($number))

2
投票
(string)floor($pecahformat[3])!=(string)$pecahformat[3]
© www.soinside.com 2019 - 2024. All rights reserved.