PHP – How to multiply two arbitrary precision numbers using bcmul() function?

PHPServer Side ProgrammingProgramming

In PHP, bcmul() math function is used to multiply one arbitrary precision number with another number. The bcmul() function takes two arbitrary precision numbers as strings and it gives the result as the multiplication of two numbers after scaling the result to an identified precision.

Syntax

string bcmul( $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 left operand and it is the string type parameter.

  • $num_string2 - It represents the right operand, it is the string type parameter.

  • $scaleVal - This 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 0.

Return Values

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

Example 1 - bcmul() PHP function without using the $scaleVal parameter

<?php
   // PHP program to illustrate bcmul() function
   // two input numbers using arbitrary precision
   $num_string1 = "10.5552";
   $num_string2 = "3";

   // calculates the addition of
   // two numbers without $scaleVal parameter
   $result = bcmul($num_string1, $num_string2);

   echo "Output without scaleVal is: ", $result;
?>

Output

Output without scaleVal is: 31

Without the scaleVal parameter, the digits after the decimal point are discarded.

Example 2 - bcmul() PHP function using the $scaleVal() parameter

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

<?php
   // PHP program to illustrate bcmul() function
   // two input numbers using arbitrary precision
   $num_string1 = "10.5552";
   $num_string2 = "3";

   // using scale value 4
   $scaleVal = 4;

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

Output

Output with scaleVal is: 31.6656
raja
Published on 21-Aug-2021 07:22:40
Advertisements