Search code examples
phplargenumber

Large Number in PHP


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."


Solution

  • 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.