compare(): order two values
compare(x, y) compares two values and returns a negative value when x is smaller, zero when they are equal, and a positive value when x is larger. This three-way result is useful in sorting rules and conditional calculations.
Why not just subtract?
For ordinary finite numbers, subtraction may suggest the order, but it does not work for text, dates, units, or many structured values. compare() states the intended operation directly and avoids treating a difference as a Boolean answer.
Choose the right comparator
For human-oriented numeric text such as “file2” before “file10”, use compareNatural(). For text-specific ordering, see compareText(). Use equal when only equality matters, larger for a Boolean greater-than test, and sort() to order a collection.
Consistency matters
Compare values of compatible types and keep one comparison rule throughout a sort. Mixed types, locale differences, and approximate floating-point values can produce surprising orderings; round or normalize data deliberately first.