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

2021-12-31 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?

How can I make the output be 10000000000000000000000000 instead?

推荐答案

这不是被 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 Multiple Precision,但默认情况下在 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;

相关文章