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

PHP: intval() equivalent for numbers gt;= 2147483647(PHP: intval() 等价于数字 gt;= 2147483647)
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)