roundTo method

dynamic roundTo({
  1. int? decimals,
  2. bool asComplex = true,
})

Returns the rounded value of this complex number.

When called without parameters, returns the integer closest to the real portion, simplifying to a num if possible.

When called with decimals, returns a new complex number with both parts rounded to the specified number of decimal places, simplifying if possible.

Examples:

Complex(3.7, 0).roundTo()         // returns 4 (int)
Complex(3.7, 2.9).roundTo()       // returns Complex(4, 3)
Complex(3.14159, 2.71828).roundTo(decimals: 2)  // returns 3.14 + 2.72i

Implementation

dynamic roundTo({int? decimals, bool asComplex = true}) {
  if (decimals == null) {
    // Handle special cases for real part
    if (real.isNaN || real.isInfinite) {
      return asComplex
          ? Complex(
              real,
              imaginary.isNaN || imaginary.isInfinite
                  ? imaginary
                  : imaginary.round())
          : real;
    }

    // Handle special cases for imaginary part
    if (imaginary.isNaN || imaginary.isInfinite) {
      return Complex(real.round(), imaginary);
    }

    // Round both parts to integers
    // Return simplified version (num or Complex)
    return asComplex
        ? Complex(real.round(), imaginary.round())
        : real.round();
  }

  final factor = math.pow(10, decimals);

  // Handle special cases
  final roundedReal =
      real.isNaN || real.isInfinite ? real : (real * factor).round() / factor;
  final roundedImag = imaginary.isNaN || imaginary.isInfinite
      ? imaginary
      : (imaginary * factor).round() / factor;

  return Complex(roundedReal, roundedImag);
}