BcMath\Number::sub

(PHP 8 >= 8.4.0)

BcMath\Number::sub任意精度数値の減算を行う

説明

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

$thisnum を減算します。

パラメータ

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

戻り値

減算結果を新しい BcMath\Number オブジェクトとして返します。

減算結果オブジェクトの BcMath\Number::scale が自動的に設定される場合、減算に使用する2つの数値のうち、 大きい方の BcMath\Number::scale が使用されます。

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

エラー / 例外

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

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

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

<?php
$number
= new BcMath\Number('1.234');

$ret1 = $number->sub(new BcMath\Number('2.34567'));
$ret2 = $number->sub('-3.456');
$ret3 = $number->sub(7);

var_dump($number, $ret1, $ret2, $ret3);
?>

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

object(BcMath\Number)#1 (2) {
  ["value"]=>
  string(5) "1.234"
  ["scale"]=>
  int(3)
}
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(8) "-1.11167"
  ["scale"]=>
  int(5)
}
object(BcMath\Number)#2 (2) {
  ["value"]=>
  string(5) "4.690"
  ["scale"]=>
  int(3)
}
object(BcMath\Number)#4 (2) {
  ["value"]=>
  string(6) "-5.766"
  ["scale"]=>
  int(3)
}

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

<?php
$number
= new BcMath\Number('1.234');

$ret1 = $number->sub(new BcMath\Number('2.34567'), 1);
$ret2 = $number->sub('-3.456', 10);
$ret3 = $number->sub(7, 0);

var_dump($number, $ret1, $ret2, $ret3);
?>

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

object(BcMath\Number)#1 (2) {
  ["value"]=>
  string(5) "1.234"
  ["scale"]=>
  int(3)
}
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(4) "-1.1"
  ["scale"]=>
  int(1)
}
object(BcMath\Number)#2 (2) {
  ["value"]=>
  string(12) "4.6900000000"
  ["scale"]=>
  int(10)
}
object(BcMath\Number)#4 (2) {
  ["value"]=>
  string(2) "-5"
  ["scale"]=>
  int(0)
}

参考

add a note

User Contributed Notes

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