10000000000000000000000000

10000000000000000000000000

本文介绍了在 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;

这篇关于在 PHP 中将一个大整数转换为一个完整的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:47