PHP:intval()等效于数字> = 2147483647 [英] PHP: intval() equivalent for numbers >= 2147483647

查看:133
本文介绍了PHP:intval()等效于数字> = 2147483647的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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

希望有所帮助!

这篇关于PHP:intval()等效于数字&gt; = 2147483647的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆