PHP – How to divide two arbitrary precision numbers using bcdiv() function?

PHPServer Side ProgrammingProgramming

In PHP, bcdiv() math function is used to divide one arbitrary precision number from another number. The bcdiv() function takes two arbitrary precision numbers as strings and it gives the result as a division of two numbers after scaling the result to an identified precision. Or, we can say that the bcdiv() PHP function divides the dividend by the divisor.

Syntax

string bcdiv($num_string1, $num_string2, $scaleVal)

Parameters

The bcmul() math function accepts three different parameters $num_string1, $num_string2 and $scaleVal.

  • $num_string1 − It represents the dividend and it is the string type parameter.

  • $num_string2 − It represents the divisor, it is the string type parameter.

  • $scaleVal  − It is the optional integer type parameter that is used to set the number of digits after the decimal place in the resulted output. It returns the default value of zero.

Return Values

The bcdiv() math function returns the multiplication of two numbers $num_str1 and num_str2, as a string.

Example 1− bcdiv() PHP function without using the $scaleVal parameter

<?php
   // PHP program to illustrate bcdiv() function
   // two input numbers using arbitrary precision
   $num_string1 = "22.5552"; // Dividend numbers
   $num_string2 = "5";       // divisor numbers
   $result = bcdiv($num_string1, $num_string2);
   echo "Output without using Scale Value: ", $result;
?>

Output

Output without using Scale Value: 4

Example 2− bcdiv() PHP function using the scaleVal parameter

Now, we will take the same input values with a scale value of 4 and check the output.

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

   // using scale value 4
   $scaleVal = 4;

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

Output

Output with Scale Value is: 4.5110
raja
Published on 21-Aug-2021 07:28:08
Advertisements