PHP:如何将bigint从int转换为string?
我希望能够将大整数转换为它们的全字符串导数.
I want to be able to convert big ints into their full string derivatives.
例如.
$bigint = 9999999999999999999;
$bigint_string = (string) $bigint;
var_dump($bigint_string);
输出
string(7) "1.0e+19"
但我需要
string(19) "9999999999999999999"
请不要告诉我,我最初应该将$ bigint值设置为字符串.那不是一个选择.我真的被困住了,不知道是否有可能?
Please don't tell me that I should just originally set the $bigint value as a string. That is not an option. I really am stuck and don't know if it is even possible?
您实际上应该确保输入您的意思:
You actually should ensure that you type what you mean:
$bigint = 9999999999999999999;
不是PHP整数,而是float:
Is not a PHP integer but float:
float(1.0E+19)
如果可以的话
$bigint = (int) 9999999999999999999;
您实际上已经设置了一个整数,但它不是您可能期望的数字:
You would have set an integer in fact, but it would not be the number you might have expected:
int(-8446744073709551616)
将其转换为字符串完全没问题,就像您可能已经猜到的那样.因此,在将数字写入代码时要小心,实际上要写出你的意思.
It's no problem at all to turn that into string as you might have guessed. So take care when you write numbers into code that you actually write what you mean.
再次查看此行:
$bigint = 9999999999999999999;
尝试了解您实际写的内容.它根本不是整数,因为PHP会将其转换为浮点数.请参见整数手册页中的示例#4在64位系统上的整数溢出 a>.
try to understand what you have actually written. It's not an integer at all because PHP will turn it into a float. See Example #4 Integer overflow on a 64-bit system in the integer manual page.
如果您需要更高的精度,请检出 GNU多精度,您正在寻找什么.但是,这不会改变在PHP中写数字的方式:
If you need higher precision, checkout GNU Multiple Precision, it might have what you're looking for. However, this won't change how to write numbers in PHP:
$bigint = gmp_init("9999999999999999999");
$bigint_string = gmp_strval($bigint);
var_dump($bigint, $bigint_string);
输出:
resource(4) of type (GMP integer)
string(19) "9999999999999999999"