PHP Integer Problem

后端 未结 5 1962
一生所求
一生所求 2021-01-14 19:42

When I print this number in php 137582392964679 I get this as the output 1.37582392965E+14

All I am doing is a simple



        
相关标签:
5条回答
  • 2021-01-14 20:08

    The manual clearly says:

    If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead.

    Also your number cannot be represented accurately because of inherent floating point limitations, hence it is being approximated.

    0 讨论(0)
  • 2021-01-14 20:10

    The maximum number you can store in a signed integer on a 32-bit machine is 2147483647. You can store numbers larger than this in a float but you risk losing some precision.

    If that's the case how can I get around this problem?

    You probably want to use a big number library. Try GMP:

    $sum = gmp_add("123456789012345", "76543210987655");
    echo gmp_strval($sum) . "\n";
    

    Result:

    200000000000000
    

    Another alternative you could use is BC Math.

    If you don't need to do any calculations with these numbers, but just store tham correctly, then store them as strings rather than integers.

    0 讨论(0)
  • 2021-01-14 20:10

    That number is too big to fit into a 32-bit integer, so yes, it is converting to a floating point type automatically. How to get around it depends on the requirements of your system. If you aren't going to do any arithmetic then just store it as a string. If precision isn't overly important then you could leave it as a float and format it using printf. If precision is important and you can upgrade to 64-bit that should fix it, if you can't upgrade and you need an integer then you could look into using the BC Math PHP extension.

    0 讨论(0)
  • 2021-01-14 20:20

    I am on a 64 bit machine and it does the same thing. You might want to try using: print number_format(137582392964679);

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

    Check the const PHP_INT_MAX. You're likely over the max, which is typically around 2 billion for a 32bit system.

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