BcMath\Number::compare

(PHP 8 >= 8.4.0)

BcMath\Number::compare任意精度数値を比較する

説明

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

任意精度数値を比較します。 このメソッドは、 宇宙船演算子 と同じように動作します。

パラメータ

num
比較する値。
scale
比較に使用する scale を指定します。 null の場合、比較にはすべての桁が使用されます。

戻り値

2つの値が等しい場合は 0$thisnum より大きい場合は 1、小さければ -1 を返します。

エラー / 例外

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

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

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

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

var_dump(
$number->compare(new BcMath\Number('1.234')),
$number->compare('1.23400'),
$number->compare('1.23401'),
$number->compare(1),
);
?>

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

int(0)
int(0)
int(-1)
int(1)

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

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

var_dump(
$number->compare(new BcMath\Number('1.299'), 1),
$number->compare('1.24', 2),
$number->compare('1.22', 2),
$number->compare(1, 0),
);
?>

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

int(0)
int(-1)
int(1)
int(0)

参考

  • bccomp() - 2 つの任意精度数値を比較する
add a note

User Contributed Notes

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