PHP – How to get the modulus of an arbitrary precision number using bcmod() function?


In PHP, bcmod() math function is used to calculate the modulus of an arbitrary precision number. The bcmod() function takes an arbitrary precision number as strings and it gives the result as a modulus of numbers after scaling the result to an identified precision. Or, we can say that it gets the remainder after dividing string_num1 by string_num2. Unless the string_num2 is 0, the result has the same sign as string_num1.

Syntax

bcmod(string_$num1, string_$num2, [, int $scale=0])

Or,

bcmod(string $dividend, string $divisor[, int $scale=0])

Note− The above syntax will get the remainder of dividing $string_num1 by $string_num2. Unless string_num2 is 0, the result has the same sign as string_num1.

Parameters

The bcmod() function accepts two different parameters, $dividend and $modulus.

  • $dividend− It represents the dividend that is divided by the given modulus value $modulus and it is the string type parameter.

  • $modulus− It is the string type parameter and it is used to represent the modulus.

Return Value

The bcmod() function returns the remainder when the dividend is divided by the modulus. If the modulus is 0, then the function returns null.

Example1 - bcmod() PHP function without using the scale parameter.

<?php
   // input numbers with arbitrary precision
   $dividend = "25.666";
   $modulus = "7";

   // calculates the modulus
   $result = bcmod($dividend, $modulus);
   echo "Output without using scale value: ", $result;
?>

Output

Output without using scale value: 4

Example 2 - bcmod() PHP function using the scale parameter

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

<?php
   // input numbers with arbitrary precision
   $dividend = "25.666";
   $modulus = "7";

   //using scale value 4
   $scaleVal =4;

   // calculates the modulus
   $result = bcmod($dividend, $modulus, $scaleVal);
   echo "Output with scale value: ", $result;
?>

Output

Output with scale value: 4.6660

Example 3

<?php
   bcscale(1);

   // 0.5 as of PHP 7.2.0; 0 previously
   echo bcmod('5.7', '1.3');
?>

Output

0.5

Note− The scale parameter was added from PHP 7.2.0 version.

Updated on: 21-Aug-2021

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements