BcMath\Number::divmod

(PHP 8 >= 8.4.0)

BcMath\Number::divmod任意精度数値の商と剰余を取得する

説明

public BcMath\Number::divmod(BcMath\Number|string|int $num, ?int $scale = null): array

$thisnum で割った商と剰余を取得します。

パラメータ

num
除数を表す値。
scale
計算結果オブジェクトの BcMath\Number::scale を明示的に指定します。 null の場合、計算結果の BcMath\Number::scale は自動的に設定されます。

戻り値

1つ目の要素に商として新しい BcMath\Number オブジェクトが、 2つ目の要素に剰余として新しい BcMath\Number オブジェクトが格納された配列を返します。

商は常に整数値となるため、商オブジェクトの BcMath\Number::scalescale の指定に関わらず、常に 0 になります。

scale を明示的に指定した場合、剰余オブジェクトの BcMath\Number::scale は指定された値になります。 剰余オブジェクトの BcMath\Number::scale が自動的に設定される場合、計算に使用された2つの数値のうち、大きい方の BcMath\Number::scale が使用されます。

つまり、2つの値の BcMath\Number::scale がそれぞれ 25 の場合、 剰余オブジェクトの BcMath\Number::scale5 になります。

エラー / 例外

このメソッドは、以下の場合に ValueError をスローします:

  • num が、BCMath で有効でない数値形式の文字列である場合
  • scale が範囲外の値である場合

このメソッドは、 num0 である場合、 DivisionByZeroError 例外をスローします。

例1 BcMath\Number::divmod()scale を指定しない例

<?php
echo '8.3 / 2.22' . PHP_EOL;
[
$quot, $rem] = new BcMath\Number('8')->divmod(new BcMath\Number('2.22'));
var_dump($quot, $rem);

echo
PHP_EOL . '8.3 / 8.3' . PHP_EOL;
[
$quot, $rem] = new BcMath\Number('8.3')->divmod('8.3');
var_dump($quot, $rem);

echo
PHP_EOL . '10 / -3' . PHP_EOL;
[
$quot, $rem] = new BcMath\Number('10')->divmod(-3);
var_dump($quot, $rem);
?>

上の例の出力は以下となります。

8.3 / 2.22
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(1) "3"
  ["scale"]=>
  int(0)
}
object(BcMath\Number)#4 (2) {
  ["value"]=>
  string(4) "1.34"
  ["scale"]=>
  int(2)
}

8.3 / 8.3
object(BcMath\Number)#2 (2) {
  ["value"]=>
  string(1) "1"
  ["scale"]=>
  int(0)
}
object(BcMath\Number)#5 (2) {
  ["value"]=>
  string(3) "0.0"
  ["scale"]=>
  int(1)
}

10 / -3
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(2) "-3"
  ["scale"]=>
  int(0)
}
object(BcMath\Number)#1 (2) {
  ["value"]=>
  string(1) "1"
  ["scale"]=>
  int(0)
}

例2 BcMath\Number::divmod()scale を指定する例

<?php
echo '8.3 / 2.22' . PHP_EOL;
[
$quot, $rem] = new BcMath\Number('8')->divmod(new BcMath\Number('2.22'), 1);
var_dump($quot, $rem);

echo
PHP_EOL . '8.3 / 8.3' . PHP_EOL;
[
$quot, $rem] = new BcMath\Number('8.3')->divmod('8.3', 4);
var_dump($quot, $rem);

echo
PHP_EOL . '10 / -3' . PHP_EOL;
[
$quot, $rem] = new BcMath\Number('10')->divmod(-3, 5);
var_dump($quot, $rem);
?>

上の例の出力は以下となります。

8.3 / 2.22
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(1) "3"
  ["scale"]=>
  int(0)
}
object(BcMath\Number)#4 (2) {
  ["value"]=>
  string(3) "1.3"
  ["scale"]=>
  int(1)
}

8.3 / 8.3
object(BcMath\Number)#2 (2) {
  ["value"]=>
  string(1) "1"
  ["scale"]=>
  int(0)
}
object(BcMath\Number)#5 (2) {
  ["value"]=>
  string(6) "0.0000"
  ["scale"]=>
  int(4)
}

10 / -3
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(2) "-3"
  ["scale"]=>
  int(0)
}
object(BcMath\Number)#1 (2) {
  ["value"]=>
  string(7) "1.00000"
  ["scale"]=>
  int(5)
}

参考

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top