toNearest method

Rational toNearest(
  1. Rational minIncrement, {
  2. RoundingMode mode = RoundingMode.halfUp,
})

Rounds the Rational value to the nearest multiple of minIncrement

Uses the specified mode for rounding (default is halfUp)

  • floor: Rounds down to the nearest multiple of minIncrement
  • ceil: Rounds up to the nearest multiple of minIncrement
  • truncate: Rounds towards zero to the nearest multiple
  • up: Rounds away from zero, increasing the magnitude of the number
  • halfUp: Rounds to the nearest multiple, rounding up on ties
  • halfDown: Rounds to the nearest multiple, rounding down on ties
  • halfEven: Rounds to the nearest multiple, choosing the even multiple on ties (banker's rounding)

If minIncrement is zero, an ArgumentError is thrown

Example:

Rational increment = Rational.fromInt(1, 4);

print(Rational.parse("7.24").toNearest(increment, mode: RoundingMode.floor));     // 7.24 --> 7.0
print(Rational.parse("7.26").toNearest(increment, mode: RoundingMode.ceil));      // 7.26 --> 7.5
print(Rational.parse("7.76").toNearest(increment, mode: RoundingMode.truncate));  // 7.76 --> 7.75
print(Rational.parse("-7.76").toNearest(increment, mode: RoundingMode.truncate)); // -7.76 --> -7.75
print(Rational.parse("7.26").toNearest(increment, mode: RoundingMode.up));        // 7.26 --> 7.5
print(Rational.parse("-7.26").toNearest(increment, mode: RoundingMode.up));       // -7.26 --> -7.5
print(Rational.parse("7.375").toNearest(increment, mode: RoundingMode.halfUp));   // 7.375 --> 7.5
print(Rational.parse("7.375").toNearest(increment, mode: RoundingMode.halfDown)); // 7.375 --> 7.25
print(Rational.parse("7.50").toNearest(increment, mode: RoundingMode.halfEven));  // 7.50 --> 7.5 (even multiple)

Throws:

  • ArgumentError: If minIncrement is zero

Implementation

Rational toNearest(Rational minIncrement, {RoundingMode mode = RoundingMode.halfUp}) {
  if (minIncrement == Rational.zero) {
    throw ArgumentError('minIncrement cannot be zero');
  }

  final Rational scaled = this / minIncrement;
  final Rational rounded = scaled.rounded(mode);
  return rounded * minIncrement;
}