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 random precision numbers as strings and it returns the addition of the two numbers after scaling the result to an identified precision.

Syntax

string bcadd ( $num_str1, $num_str2, $scaleVal)

Parameters

The bcadd() math function accepts three different parameters, $num_str1, $num_str2 and $scaleVal.

  • $num_str1 - It represents the left operand and it is the string type parameter.

  • $num_str2 - It represents the right operand and it is the string type parameter.

  • $scaleVal - It is the optional parameter that is used to set the number of digits after the decimal place in the resulted output. It returns 0 on default.

Return Values

The bcadd() math function returns the sum of two operands $num_str1 and num_str2, as a string.

Example 1 - bcadd() PHP function without using $scaleVal 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 $scaleVal
   $result = bcadd($num_string1, $num_string2);
   echo "Output without scaleVal is: ", $result;
?>

Output

Output without scaleVal is: 15

Explanation - In the above PHP example, only two parameters $num_string1 and $num_string2 are used to calculate the addition of two numbers by using bcadd() function. The $scaleval parameter is not used and it gives the output value 15 and removed the precision number after 15.

Example 2 - bcadd() PHP function using $scaleVal parameter

Now, let us use the same input values along with $scaleVal parameter and check the output.

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

   //using scale value 2
   $scaleVal = 2;

   // calculates the addition of
   // two numbers with $scaleVal parameter
   $result = bcadd($num_string1, $num_string2, $scaleVal);
   echo "Output with scaleVal is: ", $result;
?>

Output

Output with scaleVal is: 15.55

Updated on: 21-Aug-2021

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements