compareTo method

  1. @override
int compareTo(
  1. Rational other
)
override

Compares this object to another object.

Returns a value like a Comparator when comparing this to other. That is, it returns a negative integer if this is ordered before other, a positive integer if this is ordered after other, and zero if this and other are ordered together.

The other argument must be a value that is comparable to this object.

Implementation

@override
int compareTo(Rational other) {
  final thisDouble = toDouble();
  final otherDouble = other.toDouble();

  // Using operator== on floating point values isn't reliable due to potential
  // machine precision losses. Comparisons with operator> and operator< are
  // safer.
  if (thisDouble < otherDouble) {
    return -1;
  }

  if (thisDouble > otherDouble) {
    return 1;
  }

  return 0;
}