PHP Numbers Handling Very Large or Very Small Numbers - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Numbers Handling Very Large or Very Small Numbers - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

## Friday, May 10, 2019 ## PHP Numbers

### Handling Very Large or Very Small Numbers

#### Problem

You need to use numbers that are too large (or small) for PHP’s built-in floating-point
numbers.

Solution

Use either the BCMath or GMP libraries.

Using BCMath:

// \$sum = "9999999999999999"

Using GMP:

// \$sum is now a GMP resource, not a string; use gmp_strval() to convert
print gmp_strval(\$sum); // prints 9999999999999999

#### Discussion

The BCMath library is easy to use. You pass in your numbers as strings, and the function returns the sum (or difference, product, etc.) as a string. However, the range of actions you can apply to numbers using BCMath is limited to basic arithmetic.

Another option is the GMP library. While most members of the GMP family of functions accept integers and strings as arguments, they prefer to pass numbers around as resources, which are essentially pointers to internal representations of the numbers.

So unlike BCMath functions, which return strings, GMP functions return only resources.  You then pass the resource to any GMP function, and it acts as your number.

The only downside is that when you want to view or use the resource with a non-GMP function, you need to explicitly convert it using gmp_strval() or gmp_intval(). GMP functions are liberal in what they accept.

\$four = gmp_add(2, 2);                   // You can pass integers
\$eight = gmp_add('4', '4');               // Or strings
\$twelve = gmp_add(\$four, \$eight); // Or GMP resources

However, you can do many more things with GMP numbers than addition, such as raising a number to a power, computing large factorials very quickly, finding a greatest common divisor (GCD), and other fancy mathematical stuff

Example   Computing fancy mathematical stuff using GMP

// Raising a number to a power
\$pow = gmp_pow(2, 10);

// Computing large factorials very quickly
\$factorial = gmp_fact(20);

// Finding a GCD
\$gcd = gmp_gcd(123, 456);

// Other fancy mathematical stuff
\$legendre = gmp_legendre(1, 7);

The BCMath and GMP libraries aren’t necessarily enabled with all PHP configurations. BCMath is bundled with PHP, so it’s likely to be available. However, GMP isn’t bundled with PHP, so you’ll need to download, install it, and instruct PHP to use it during the configuration process. Check the values of function_defined('bcadd') and function_defined('gmp_init') to see if you can use BCMath and GMP.

\$two = bi_from_str('2');
// Use bi_to_str() to get strings from big_int resources
print bi_to_str(\$four); // prints 4

// Computing large factorials very quickly
\$factorial = bi_fact(20);