PHP: intval() 等价于数字 >= 2147483647

2022-01-17 00:00:00 numbers integer types php

在 PHP 5 中,每当我将数字作为输入时,我都会使用 intval().这样,我想确保我没有得到字符串或浮点数.我的输入数字应该都是整数.但是当我得到数字 >= 2147483647 时,就超过了有符号整数限制.

In PHP 5, I use intval() whenever I get numbers as an input. This way, I want to ensure that I get no strings or floating numbers. My input numbers should all be in whole numbers. But when I get numbers >= 2147483647, the signed integer limit is crossed.

如何为所有大小的数字设置一个等效的 intval()?

What can I do to have an intval() equivalent for numbers in all sizes?

这是我想要的:

<?php
$inputNumber = 3147483647.37;
$intNumber = intvalEquivalent($inputNumber);
echo $intNumber; // output: 3147483647
?>

非常感谢您!

根据一些答案,我尝试编写等效函数.但它还不能像 intval() 那样工作.我该如何改进它?它有什么问题?

Based on some answers, I've tried to code an equivalent function. But it doesn't work exactly as intval() does yet. How can I improve it? What is wrong with it?

function intval2($text) {
    $text = trim($text);
    $result = ctype_digit($text);
    if ($result == TRUE) {
        return $text;
    }
    else {
        $newText = sprintf('%.0f', $text);
        $result = ctype_digit($newText);
        if ($result == TRUE) {
            return $newText;
        }
        else {
             return 0;
        }
    }
}

推荐答案

试试这个功能,它会像 intval 一样正确删除任何小数,并删除所有非数字字符.

Try this function, it will properly remove any decimal as intval does and remove any non-numeric characters.

<?php
function bigintval($value) {
  $value = trim($value);
  if (ctype_digit($value)) {
    return $value;
  }
  $value = preg_replace("/[^0-9](.*)$/", '', $value);
  if (ctype_digit($value)) {
    return $value;
  }
  return 0;
}

// SOME TESTING
echo '"3147483647.37" : '.bigintval("3147483647.37")."<br />";
echo '"3498773982793749879873429874.30872974" : '.bigintval("3498773982793749879873429874.30872974")."<br />";
echo '"hi mom!" : '.bigintval("hi mom!")."<br />";
echo '"+0123.45e6" : '.bigintval("+0123.45e6")."<br />";
?>

这是生成的输出:

"3147483647.37" : 3147483647
"3498773982793749879873429874.30872974" : 3498773982793749879873429874
"hi mom!" : 0
"+0123.45e6" : 0

希望有帮助!

相关文章