rounded method

Rational rounded([
  1. RoundingMode mode = RoundingMode.halfUp
])

Rounds the Rational value according to the specified mode

Uses the specified mode for rounding (default is halfUp)

The rounding behavior varies based on the mode:

  • floor: Rounds down to the nearest lower integer
  • ceil: Rounds up to the nearest higher integer
  • truncate: Rounds towards zero, removing the fractional part
  • up: Rounds away from zero, increasing the magnitude of the number
  • halfUp: Rounds to the nearest integer, rounding up if exactly halfway
  • halfDown: Rounds to the nearest integer, rounding down if exactly halfway
  • halfEven: Rounds to the nearest integer; if exactly halfway, rounds to the nearest even integer

Example:

print(Rational.parse("7.51").rounded(RoundingMode.floor));     // 7.51 --> 7
print(Rational.parse("7.01").rounded(RoundingMode.ceil));      // 7.01 --> 8
print(Rational.parse("7.99").rounded(RoundingMode.truncate));  // 7.99 --> 7
print(Rational.parse("-7.99").rounded(RoundingMode.truncate)); // -7.99 --> -7
print(Rational.parse("7.01").rounded(RoundingMode.up));        // 7.01 --> 8
print(Rational.parse("-7.01").rounded(RoundingMode.up));       // -7.01 --> -8
print(Rational.parse("7.5").rounded(RoundingMode.halfUp));     // 7.5  --> 8
print(Rational.parse("7.5").rounded(RoundingMode.halfDown));   // 7.5  --> 7
print(Rational.parse("7.5").rounded(RoundingMode.halfEven));   // 7.5  --> 8 (rounds up to even)
print(Rational.parse("8.5").rounded(RoundingMode.halfEven));   // 8.5  --> 8 (rounds down to even)

Implementation

Rational rounded([RoundingMode mode = RoundingMode.halfUp]) {
  final BigInt wholeNumber = truncate(); // Extract integer part
  final Rational fraction = this - Rational(wholeNumber); // Extract fractional part

  // If it's already an integer, return as is
  if (fraction == Rational.zero) {
    return this;
  }

  switch (mode) {
    case RoundingMode.floor:
      return fraction < Rational.zero ? Rational(wholeNumber - BigInt.one) : Rational(wholeNumber);

    case RoundingMode.ceil:
      return fraction > Rational.zero ? Rational(wholeNumber + BigInt.one) : Rational(wholeNumber);

    case RoundingMode.truncate:
      return Rational(wholeNumber);

    case RoundingMode.up:
      // Round up for positive numbers, down for negative
      return fraction > Rational.zero ? Rational(wholeNumber + BigInt.one) : Rational(wholeNumber - BigInt.one);

    case RoundingMode.halfUp:
      return _roundedHalf(wholeNumber, fraction, roundUp: true);

    case RoundingMode.halfDown:
      return _roundedHalf(wholeNumber, fraction, roundUp: false);

    case RoundingMode.halfEven:
      return _roundedHalfEven(wholeNumber, fraction);
  }
}