Home  >  Article  >  Backend Development  >  PHP - How to add two arbitrary precision numbers using bcadd() function?

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

WBOY
WBOYforward
2023-09-14 18:37:02840browse

PHP – 如何使用bcadd()函数添加两个任意精度的数字?

In PHP, the bcadd() mathematical function is used to add two arbitrary-precision numbers. bcadd() The function takes two random precision numbers as strings and returns the addition of the two numbers after scaling the result to a determined precision.

Syntax

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

Parameters

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

  • $num_str1 - represents the left operand, which is a string type parameter.

  • $num_str2 - represents the right operand, which is a string type parameter.

  • $scaleVal - Optional parameter used to set the number of digits after the decimal point in the result output. Default returns 0.

Return value

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

Example 1 - bcadd() PHP function without $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, Computing addition using only two arguments $num_string1 and $num_string2 uses the bcadd() function to compute two numbers. The $scaleval argument is not used, which gives an output value of 15, with precision digits after 15 removed.

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

Now, let us use the same input value and $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

The above is the detailed content of PHP - How to add two arbitrary precision numbers using bcadd() function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete