Introduction
Decimal numbers of any size for PHP, built on the BCMath extension. Every number is an immutable value object.
Requirements#
The library needs a current PHP version and the BCMath extension, which does the calculations.
- PHP 8.4 or newer
- The
bcmathextension
Installation#
Install the library with Composer. This also checks that the BCMath extension is available.
composer require phpmath/bignumber
A first example#
Create a number from a string, an int or a float. Use a string for anything with many digits, because a string never loses precision. The second argument is the scale, which is the number of decimals the number keeps.
use PHPMath\BigNumber\BigNumber;
$a = new BigNumber('12345678901234567890.5', 2);
$b = new BigNumber('0.25');
$sum = $a->add($b);
echo $sum->getValue(); // 12345678901234567890.75
echo $a; // 12345678901234567890.50
Calling add() did not change $a. It returned a new BigNumber. This is true for every operation in the library.
Where to go next#
Start with the core concepts, or jump straight to the topic you need.
Core conceptsImmutability, creating values and reading them.Scale and truncationHow many decimals a number keeps and what happens to the rest.ArithmeticAdd, divide, modulo, powers and square roots.Input formatsWhich strings, ints and floats are accepted.Base conversionConvert integers between bases 2 and 36.API referenceEvery method with its parameters and errors.