PHP 8.4.3 Released!

BcMath\Number::compare

(PHP 8 >= 8.4.0)

BcMath\Number::compareCompares two arbitrary precision numbers

Beschreibung

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

Compare two arbitrary precision numbers. This method behaves similar to the spaceship operator.

Parameter-Liste

num
The value to be compared to.
scale
Specify the scale to use for comparison. If null, all digits are used in the comparison.

Rückgabewerte

Returns 0 if the two numbers are equal, 1 if $this is greater than num, -1 otherwise.

Fehler/Exceptions

This method throws a ValueError in the following cases:

  • num is string and not a well-formed BCMath numeric string
  • scale is outside the valid range

Beispiele

Beispiel #1 BcMath\Number::compare() example when scale is not specified

<?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),
);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #2 BcMath\Number::compare() example of explicitly specifying 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),
);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • bccomp() - Vergleich zweier Zahlen beliebiger Genauigkeit
add a note

User Contributed Notes

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