Large numbers in PHP are not what they seem to be

前端 未结 3 1584
独厮守ぢ
独厮守ぢ 2021-01-27 20:07

I agree with this

php > var_dump(number_format(10000000000000000000000)); // 10^22
php shell code:1:
string(30) \"10,000,000,000,000,000,000,000\"


        
相关标签:
3条回答
  • 2021-01-27 20:14

    This is well-described in the documentation:

    Integer overflow

    If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

    Example #3 Integer overflow on a 64-bit system

    <?php
    $large_number = 9223372036854775807;
    var_dump($large_number);                     // int(9223372036854775807)
    
    $large_number = 9223372036854775808;
    var_dump($large_number);                     // float(9.2233720368548E+18)
    
    $million = 1000000;
    $large_number =  50000000000000 * $million;
    var_dump($large_number);                     // float(5.0E+19)
    ?>
    

    There are many values that floating-point numbers can't exactly represent. See Is floating point math broken? for details.

    The PHP_INT_MAX constant shows the largest integer your version of PHP supports.

    0 讨论(0)
  • 2021-01-27 20:29

    Change the precisiona in php.ini or use ini_set and apply cast in your var

    ini_set('precision', 2048);
    $number1 = (float) "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001";
    $number3 = (float) "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001";
    
    $test1 = (0 == $number1);
    $test2 = (0 == $number3);
    
    0 讨论(0)
  • 2021-01-27 20:35

    Floating point numbers.

    Computer memory is limited, so storing an infinitely precise integer value is impossible. Your system basically ran out of room for precise integer valuation.

    This answer does a great job talking about how to get the integer to appear at the number you want it though.

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