Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 arbitrary precision numbers as strings and returns the remainder after dividing the dividend by the divisor. Unless the divisor is 0, the result has the same sign as the dividend.
Syntax
bcmod(string $dividend, string $divisor[, int $scale = 0])
Note − The scale parameter was added from PHP 7.2.0 version.
Parameters
The bcmod() function accepts the following parameters ?
$dividend − The dividend that is divided by the divisor (string type)
$divisor − The divisor used to calculate the modulus (string type)
$scale − Optional. Sets the number of digits after the decimal point (default is 0)
Return Value
The bcmod() function returns the remainder when the dividend is divided by the divisor as a string. If the divisor is 0, then the function returns null.
Example 1 - Basic bcmod() Usage
Here's a simple example without using the scale parameter ?
<?php
// input numbers with arbitrary precision
$dividend = "25.666";
$divisor = "7";
// calculates the modulus
$result = bcmod($dividend, $divisor);
echo "Output without using scale value: " . $result;
?>
Output without using scale value: 4
Example 2 - Using Scale Parameter
Now, we will use the same input values with a scale value of 4 ?
<?php
// input numbers with arbitrary precision
$dividend = "25.666";
$divisor = "7";
$scaleVal = 4;
// calculates the modulus with scale
$result = bcmod($dividend, $divisor, $scaleVal);
echo "Output with scale value: " . $result;
?>
Output with scale value: 4.6660
Example 3 - Using bcscale()
You can also set a global scale using bcscale() function ?
<?php
bcscale(1);
// calculates modulus with global scale
echo bcmod('5.7', '1.3');
?>
Output: 0.5
Conclusion
The bcmod() function is essential for precise modulus calculations with arbitrary precision numbers. Use the scale parameter to control decimal precision in your results.
