Comparing quantities
Comparison methods operate on native values, so two quantities expressed in different
units compare correctly. Unlike add() and subtract(), comparison methods require the
operands to be the same quantity type and throw InvalidArgumentException otherwise.
Ordering methods
use Renfordt\UnitLib\Length;
$a = new Length(1, 'km');
$b = new Length(500, 'm');
$c = new Length(1000, 'm');
$a->greaterThan($b); // true
$a->lessThan($b); // false
$a->greaterThanOrEqualTo($c); // true
$a->lessThanOrEqualTo($c); // true
compareTo
compareTo() returns -1, 0, or 1, which makes it directly usable as a sort
comparator:
$lengths = [
new Length(5, 'm'),
new Length(200, 'cm'),
new Length(3000, 'mm'),
];
usort($lengths, fn($a, $b) => $a->compareTo($b));
// Ordered: 2 m, 3 m, 5 m
Equality
equals() compares native values within a tolerance to account for floating-point
rounding. The default tolerance is 1e-10; pass a different epsilon as the second
argument:
$a = new Length(1, 'km');
$a->equals(new Length(1000, 'm')); // true
$a->equals(new Length(1000, 'm'), 0.001); // true with a wider tolerance
Type checking
All comparison methods reject operands of a different quantity type:
use Renfordt\UnitLib\{Length, Mass};
(new Length(1, 'm'))->greaterThan(new Mass(1, 'kg'));
// InvalidArgumentException: Cannot compare ...Length with ...Mass