Search code examples
phpgmp

PHP - GMP and floating point numbers?


The following code outputs 0, which isn't correct:

$r = gmp_pow(gmp_init('-1.7976931348623157'), 308);
echo gmp_strval($r);

I was under the impression that the GMP library was capable of handling floating point numbers, or have I made a mistake in the code?


Solution

  • GMP library was capable of handling floating point numbers,

    It's not. You can test that with:

    echo gmp_strval(gmp_init('18')); // 18
    echo gmp_strval(gmp_init('1.8')); // 0
    

    Now, what you could do is use BCMath instead:

    $num = bcpow('-1.7976931348623157', '308');
    echo $num;
    echo floatval($num); // for a "prettier" format