Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

2.13. 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 = bcadd('1234567812345678', '8765432187654321');

// $sum is now the string '9999999999999999'
print $sum;

Using GMP:

$sum = gmp_add('1234567812345678', '8765432187654321');

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

Discussion

The BCMath library is easy to use. You pass in your numbers as strings, and the function return 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.

The GMP library is available as of PHP 4.0.4. 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 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 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. For instance:

$four = gmp_add(2, 2); // You can pass integers $eight = gmp_add('4', '4'); // Or strings $twelve = gmp_add($four, $eight); // Or GMP resources ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata