PHP中的大数[重复]

nhn9ugyo  于 2023-05-05  发布在  PHP
关注(0)|答案(2)|浏览(123)

此问题已在此处有答案

(PHP) How to avoid scientific notation and show the actual large numbers? [duplicate](2个答案)
9年前关闭。
我在PHP中遇到了一个大问题。我的大数将被插入数据库,但一切都出错了。
案例一:

$testNumber = "1111111111111111";
$num = $testNumber*1;
echo $num;                           // --> 1.11111111111E+15   (wrong)
echo number_format($num,0,"","");    // --> 1111111111111111    (right)

案例二:

$testNumber = "11111111111111111";
$num = $testNumber*1;
echo $num;                           // --> 1.11111111111E+16   (wrong)
echo number_format($num,0,"","");    // --> 11111111111111112   (wrong)

案例三:

$testNumber = "111111111111111111";
$num = $testNumber*1;
echo $num;                           // --> 1.11111111111E+17   (wrong)
echo number_format($num,0,"","");    // --> 111111111111111104  (wrong)

我该如何解决这个问题?
先谢谢你了!

感谢Wyzard的建议。这是我的解决方案:

$testNumber = "11111111111111111111";
$num = bcmul($testNumber,1);
echo $num;                           // --> 11111111111111111111   (right)

这是非常重要的信息

“自PHP 4.0.4起,libbcmath与PHP捆绑在一起。此扩展不需要任何外部库。"

pcww981p

pcww981p1#

这些数字太大,无法放入integer中,因此PHP将其视为floats。浮点数的精度有限;它们基本上是scientific notation,只有有限数量的significant figures。听起来你快达到精度极限了。
您可能希望使用PHP的BCMathGMP扩展来处理可能非常大的数字。

cfh9epnr

cfh9epnr2#

对于这种情况,我使用GMP扩展(http://php.net/manual/en/book.gmp.php)。首先将数字作为字符串发送到gmp_init(http://www.php.net/manual/en/function.gmp-init.php),然后使用gmp_...函数,然后使用gmp_strval(http://www.php.net/manual/en/function.gmp-strval.php)将结果作为字符串检索

相关问题