Convert a big integer to a full string in PHP

前端 未结 4 1267
失恋的感觉
失恋的感觉 2020-12-03 23:12

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 e

相关标签:
4条回答
  • 2020-12-03 23:29

    UPDATE: Found the next post:

    // strval() will lose digits around pow(2,45);
    echo pow(2,50); // 1.1258999068426E+015
    echo (string)pow(2,50); // 1.1258999068426E+015
    echo strval(pow(2,50)); // 1.1258999068426E+015
    
    // full conversion
    printf('%0.0f',pow(2,50)); // 112589906846624
    echo sprintf('%0.0f',pow(2,50)); // 112589906846624
    

    Use printf or sprintf.

    0 讨论(0)
  • 2020-12-03 23:35

    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.

    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.

    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;
    
    0 讨论(0)
  • 2020-12-03 23:38

    I'm facing this problem when getting facebook id and find it in MySQL. And after half hour, i found this work perfectly! Insert this line to your php script:

    ini_set('precision',30);
    

    From: https://forums.phpfreaks.com/topic/125907-solved-convert-big-number-to-string/#entry651084

    0 讨论(0)
  • 2020-12-03 23:40

    The integer number you like to express:

    $var = 10000000000000000000000000;
    

    is not available on your system. It's too large and therefore PHP converts it into a float which will change the number (32 bit system example):

           10000000000000000905969664
    

    Common limits are:

     yours :  10 000 000 000 000 000 000 000 000
     32 bit:                       2 147 483 648
     64 bit:           9 223 372 036 854 775 808
    

    The change of the value is called floating point precision, the PHP manual about integers will tell you about the integer limit and the floats page about floating point precision (see the big red warning). Depending on which system you are, you can compile PHP with the ranges your application needs or you must use another datatype, for example with the gmp library which is able to pick strings as integer numbers and handle them.

    The following example shows just output, but you can do multiplications etc.:

    $r = gmp_init('10000000000000000000000000');
    echo gmp_strval($r);
    

    Hope this is helpful.

    0 讨论(0)
提交回复
热议问题