在 PHP 中将一个大整数转换为一个完整的字符串

2022-01-12 00:00:00 integer type-conversion casting php

我已经找了一段时间了,但我能找到的不是我要找的.我需要将一个可能非常大的整数值转换为字符串.听起来很简单:"$var"?不,因为这会导致数字的 E+ 表示.

I've been searching for a while now, but what I can find is not what I search for. I need to convert an integer value, that may be very huge, to a string. Sounds easy: "$var"? No, because this can lead to the E+ representation of the number.

<?php

$var = 10000000000000000000000000;
echo $var."
";
echo "'$var'
";
echo (string) $var."
";
echo strval($var);

?>

1.0E+25
'1.0E+25'
1.0E+25
1.0E+25

如何使输出改为 10000000000000000000000000?

推荐答案

PHP 存储的不是整数,而是浮点数,这就是为什么你最终得到 1.0E+25 而不是 10000000000000000000000000 的原因.

This is not stored as an integer by PHP, but a float, this is why you end up with 1.0E+25 instead of 10000000000000000000000000.

遗憾的是,无法在 PHP 中将其用作整数值,因为 PHP 无法保存该大小的整数.如果这来自数据库,那么它将是一个字符串,您可以随心所欲地使用它.如果将其存储在其他位置,则将其存储为字符串.

It's sadly not possible to use that as an integer value in PHP, as PHP cannot save an integer of that size. If this comes from database then it will be a string and you can do with it whatever you want. If you store it elsewhere then store it as a string.

您的替代方法是将其存储为浮点数并始终将其考虑在内,尽管这需要额外的转换和在某些地方进行处理.

Your alternative is to store it as a float and take that into account at all times, though that requires additional conversions and handling in places.

也有人建议使用 GNU 多精度,但 PHP 默认不启用.

It's also been suggested to use GNU Multiple Precision, but that's not enabled in PHP by default.

$int=gmp_init("10000000000000000000000000");
$string=gmp_strval($int);
echo $string;

相关文章