Run math operations with BCMath\Number in PHP 8.4

Video Lesson: Run math operations with BCMath\Number in PHP 8.4

Lesson Content

PHP 8.4 introduces a new BCMath\Number class that makes working with arbitrary precision numbers much easier and more intuitive. This allows you to perform accurate decimal calculations using familiar object syntax instead of procedural functions.

Before PHP 8.4, we had to use awkward function calls like bcadd() for precision math:

$num1 = '1.234';
$num2 = '5';
$result = bcadd($num1, $num2, 3);

echo $result; // 6.234

With PHP 8.4, we can now use object syntax and standard math operators:

$num1 = new \BCMath\Number('1.234');
$num2 = new \BCMath\Number('5');
$result = $num1 + $num2;

echo $result; // 6.234

The new class supports all standard math operators, making your code much more readable.

You can also chain method calls when dealing with complex operations:

$num1 = new \BCMath\Number('1.234');
$num2 = new \BCMath\Number('5');
$result = ($num1 + $num2)->add('9')->mul(2);

echo $result; // 30.468

The BCMath\Number class also includes useful methods for rounding:

$num1 = new \BCMath\Number('5.678');

echo $num1->round(1); // 5.7
echo $num1->ceil();   // 6
echo $num1->floor();  // 5

For comparison operations, the compare() method returns -1, 0, or 1 (less than, equal to, or greater than):

$num1 = new \BCMath\Number('1.234');
$num2 = new \BCMath\Number('5');
$result = $num1->compare($num2)

echo $result; // -1 (since 1.234 is less than 5)

This approach makes your code cleaner and more maintainable, especially when dealing with financial figures and calculations, along with any other scenario that requires precise decimal math.