toNearestDecimal method
Rounds the rational number to the nearest decimal place
Returns a Rational value rounded to the specified number of decimal places. For formatted string output, see RationalFormattingExtension.toDecimalString.
Parameters:
decimalPlaces: The number of decimal places to round tomode: The rounding mode to apply. Defaults to RoundingMode.halfUp
Returns: The rational number rounded to the nearest decimal place (as a Rational)
See also:
- toCents for a common case of 2 decimal places
- toNearest for rounding to arbitrary increments
- toNearestHalf, toNearestThird, toNearestQuarter for common fractions
Implementation
Rational toNearestDecimal(int decimalPlaces, {RoundingMode mode = RoundingMode.halfUp}) {
if (decimalPlaces < 0) {
throw ArgumentError('The number of decimal places must be non-negative.');
}
final scale = Rational(BigInt.from(10).pow(decimalPlaces));
return (this * scale).rounded(mode) / scale;
}