PHP中的大数字

时间:2013-11-21 07:44:03

标签: php largenumber

我在PHP中遇到大量问题。我的大号将被插入到数据库中,但一切都出错了。

案例1:

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

案例2:

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

案例3:

$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捆绑在一起。此扩展不需要任何外部库。”

2 个答案:

答案 0 :(得分:4)

这些数字太大而无法放入integer,因此PHP会将它们视为floats。浮点数的精度有限;它们基本上是scientific notation,数量有限significant figures。听起来你正在达到精确限制。

您可能希望使用PHP的BCMathGMP扩展来处理可能非常大的数字。

答案 1 :(得分:1)

对于这种情况,我使用了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

将结果检索为字符串