结论: Marc B的解决方案是64位,但对于32位我不确定你能否获得所需的准确度
更新#1: 19字符长度是字符串/数字最大长度
UPDATE#2:这种方式有效,但只有当数字是字符串格式时才会这样:
$number = "12345678901234567890";
如果我像这样传递
$number = 12345678901234567890;
我收到警告:
警告:gmp_abs():无法将变量转换为GMP - 错误类型
更新了课程
class StringToInteger {
public static function getInteger($number) {
//return sprintf('%.0f', $number);
//$number = sprintf('%d', $number);
$number = gmp_abs($number);
return gmp_strval($number);
}
}
下面的原始问题:
我有一些数据以字符串或整数形式传递(思考电话号码但更长),大多数数据只是一个很长的数字:
1234567890123456789
但有时它会像这样
123-456-789-012-345-678-9 // could be other non numeric characters as well
使用以下功能无法获得所需的结果
class StringToInteger {
public static function getInteger($number) {
return number_format($number, 0, '.', '');
}
}
class NumericOnly {
public static function formatNumber($number) {
return preg_replace("/[^\d]/", "", $number);
}
}
传递为数字:
$number = 1234567890123456789;
// output: 1.23456789012E+18 can't use this
echo "Number: {$number}\n";
// Where did my number go? truncated/rounded?
// output: 12345678901218 can't use this
echo "Numeric Only: ".NumericOnly::formatNumber($number)."\n";
// Where did my number go? truncated?
// output: 1234567890123456768 can't use this
echo "String To Integer: ".StringToInteger::getInteger($number)."\n";
传递为字符串:
$string = '1234567890123456789';
// output: 1234567890123456789
echo "String Number: {$string}\n";
// Works
// output: 1234567890123456789
echo "String Numeric Only: ".NumericOnly::formatNumber($string)."\n";
// Where did my number go? truncated?
// output: 1234567890123456768 can't use this
echo "String To Integer: ".StringToInteger::getInteger($string)."\n";
// After Conversion, truncated?
// output: 1234567890123456768 can't use this
echo "After String To Integer: ";
echo StringToInteger::getInteger(NumericOnly::formatNumber($string))."\n";
Alpha数字
$string = '123-456-789-012-345-678-9';
// output: 123-456-789-012-345-678-9 can't use this
echo "String Number: {$string}\n";
// Works
// output: 1234567890123456789
echo "String Numeric Only: ".NumericOnly::formatNumber($string)."\n";
// After Conversion, truncated?
// output: 1234567890123456768 can't use this
echo "After String To Integer: ";
echo StringToInteger::getInteger(NumericOnly::formatNumber($string))."\n";
关于如何获得长整数(完整正确的数字)的任何想法?