PHP – How to add two arbitrary precision numbers using bcadd() function?

In PHP, bcadd() math function is used to add two arbitrary precision numbers. The bcadd() function takes two arbitrary precision numbers as strings and returns their sum, scaling the result to a specified precision.

Syntax

string bcadd(string $num1, string $num2, int $scale = 0)

Parameters

The bcadd() function accepts three parameters −

  • $num1 − The left operand as a string representing an arbitrary precision number.

  • $num2 − The right operand as a string representing an arbitrary precision number.

  • $scale − Optional parameter that sets the number of digits after the decimal point in the result. Default is 0.

Return Value

The bcadd() function returns the sum of the two operands as a string.

Example 1 − Basic Addition Without Scale

Let's demonstrate bcadd() without specifying the scale parameter −

<?php
    // PHP program to illustrate bcadd() function
    // two input numbers using arbitrary precision
    $num_string1 = "5";
    $num_string2 = "10.555";

    // calculates the addition of
    // the two numbers without scale
    $result = bcadd($num_string1, $num_string2);
    echo "Output without scale is: " . $result;
?>
Output without scale is: 15

Explanation − When the scale parameter is not specified, bcadd() defaults to 0 decimal places, truncating the result to the nearest integer.

Example 2 − Addition With Scale Parameter

Now, let's use the same input values with a specified scale parameter −

<?php
    // PHP program to illustrate bcadd() function with scale
    $num_string1 = "5";
    $num_string2 = "10.555";
    
    // using scale value 2
    $scaleVal = 2;

    // calculates the addition with scale parameter
    $result = bcadd($num_string1, $num_string2, $scaleVal);
    echo "Output with scale 2 is: " . $result;
?>
Output with scale 2 is: 15.55

Example 3 − High Precision Calculation

The bcadd() function is particularly useful for high−precision calculations −

<?php
    $num1 = "123456789.123456789";
    $num2 = "987654321.987654321";
    
    // Addition with high precision
    $result = bcadd($num1, $num2, 6);
    echo "High precision result: " . $result;
?>
High precision result: 1111111111.111111

Conclusion

The bcadd() function is essential for precise arithmetic operations in PHP, especially when dealing with financial calculations or scientific computations where floating−point precision matters. Always specify the scale parameter for consistent decimal place formatting.

Updated on: 2026-03-15T09:53:08+05:30

517 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements