bcmod

(PHP 4, PHP 5, PHP 7, PHP 8)

bcmod任意精度数字取模

说明

bcmod(string $num1, string $num2, ?int $scale = null): string

num1 使用 num2 取模。结果与 num1 的符号相同。

参数

num1

左操作数,字符串类型。

num2

右操作数,字符串类型。

scale
此参数用于设置结果小数点后的位数。 如果为 null,则默认为使用 bcscale() 设置的默认精度, 或者回退到 bcmath.scale INI 指令的值。

返回值

返回字符串类型取模后的结果。

错误/异常

此函数在下列情况下抛出 ValueError

  • num1num2 不是格式正确的 BCMath 数字字符串。
  • scale 超出有效范围。

如果 num20,此函数会抛出 DivisionByZeroError 异常。

更新日志

版本 说明
8.0.0 现在 scale 可以为 null。
8.0.0 现在,除以 0 会引发 DivisionByZeroError 异常,而不是返回 null
7.2.0 现在 num1num2 不会截断成整数。 所以现在 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
?>

参见

  • bcdiv() - 两个任意精度的数字除法计算
  • bcdivmod() - Get the quotient and modulus of an arbitrary precision number
  • BcMath\Number::mod() - Gets the modulus of an arbitrary precision number