toNearest method
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 ofminIncrementceil: Rounds up to the nearest multiple ofminIncrementtruncate: Rounds towards zero to the nearest multipleup: Rounds away from zero, increasing the magnitude of the numberhalfUp: Rounds to the nearest multiple, rounding up on tieshalfDown: Rounds to the nearest multiple, rounding down on tieshalfEven: 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: IfminIncrementis 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;
}