سؤال

I have a problem with large number in PHP. My large number will be inserted into the database but everything go wrong.

case 1:

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

case 2:

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

case 3:

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

How can I solve this problem?

Thanks in advance!


Thank Wyzard for his suggestion. This is my solution:

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

and this is very important information:

"Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension."

هل كانت مفيدة؟

المحلول

Those numbers are too large to fit in an integer, so PHP treats them as floats instead. Floating-point numbers have limited precision; they're essentially scientific notation, with a limited number of significant figures. It sounds like you're running into that precision limit.

You may want to use PHP's BCMath or GMP extensions for working with numbers that may be very large.

نصائح أخرى

For such cases I used the GMP extension (http://php.net/manual/en/book.gmp.php). You start by sending the number as a string to gmp_init (http://www.php.net/manual/en/function.gmp-init.php), then work using gmp_... functions and then retrieve the result as a string using gmp_strval (http://www.php.net/manual/en/function.gmp-strval.php)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top