bcmod
(PHP 4, PHP 5, PHP 7, PHP 8)
bcmod — 任意精度数字取模
说明
bcmod(string
$num1
, string $num2
, ?int $scale
= null
): string
对 num1
使用 num2
取模。
除非 num2
是零,否则结果必定和 num1
有相同的符号。
参数
-
num1
-
string 类型的被除数。
-
num2
-
string 类型的除数。
返回值
返回字符串类型取模后的结果,如果 num2
为 0 则返回 null
。
更新日志
版本 | 说明 |
---|---|
8.0.0 |
现在 scale 可以为 null。
|
7.2.0 |
现在
num1 和 num2 不会截断成整数。
所以现在 bcmod() 的表现更接近 fmod()
而不是 % 操作符。
|
7.2.0 |
新增参数 scale 。
|
范例
示例 #1 bcmod() 示例
<?php
bcscale(0);
echo bcmod( '5', '3'); // 2
echo bcmod( '5', '-3'); // 2
echo bcmod('-5', '3'); // -2
echo bcmod('-5', '-3'); // -2
?>
示例 #2 带小数点的 bcmod()
<?php
bcscale(1);
echo bcmod('5.7', '1.3'); // PHP 7.2.0 起是 0.5;之前是 0
?>

User Contributed Notes 2 notes
lauris at night dot lt ¶
18 years ago
<?php
/**
* my_bcmod - get modulus (substitute for bcmod)
* string my_bcmod ( string left_operand, int modulus )
* left_operand can be really big, but be carefull with modulus :(
* by Andrius Baranauskas and Laurynas Butkus :) Vilnius, Lithuania
**/
function my_bcmod( $x, $y )
{
// how many numbers to take at once? carefull not to exceed (int)
$take = 5;
$mod = '';
do
{
$a = (int)$mod.substr( $x, 0, $take );
$x = substr( $x, $take );
$mod = $a % $y;
}
while ( strlen($x) );
return (int)$mod;
}
// example
echo my_bcmod( "7044060001970316212900", 150 );
?>
drahoszdenek at gmail dot com ¶
9 years ago
The modulus can be only integer. For "floats" bcmod returns 0:
<?php
echo bcmod('10', '2.1'); // 0
?>
For real modulus you can use BN-PHP project (hosted at Bitbucket):
<?php
$eval = new \BN\Expression\ExpressionEvaluator();
$operators = new \BN\Expression\OperatorsFactory();
$eval->setOperators($operators->getOperators(array('%')));
echo $eval->evaluate('10 % 2.1'); // 1.6
echo $eval->evaluate('10 % -2.1'); // 1.6
echo $eval->evaluate('-10 % 2.1'); // -1.6
echo $eval->evaluate('-10 % -2.1'); // -1.6
?>