Question

Context: .Net, C#

I want to print a complex number made from two doubles. The sign needs to show on the imaginary part. I'd like to use the default double formatting for each part to minimize the number of characters.

I tried using String.Format("{0:+G;-G}{1:+G;-G}j", real, imaginary) but this ended up printing: "+G-Gj". Not quite what I wanted.

Is there any way to do this using the G specifier or do I need to do a custom format which would sacrifice auto-switching the exponent, e.g. {1:+#.######e###;-#.######e###}j"

Was it helpful?

Solution

it is unusual, but you can easily override your Complex class's ToString method. For example:

  class Complex {
    private double mReal, mImaginary;
    public Complex(double real, double imag) { mReal = real; mImaginary = imag; }
    private string WithSign(double value) {
      return value >= 0 ? "+" + value.ToString("N") : value.ToString("N");
    }
    public override string ToString() {
      return WithSign(mReal) + "i" + WithSign(mImaginary);
    }
  }

Sample usage:

  static void Main(string[] args) {
    var c = new Complex(1, -1);
    Console.WriteLine(c.ToString());
    Console.ReadLine();
  }

Output:

  +1.00i-1.00

Tweak as necessary.

OTHER TIPS

This is probably way off...

How about something like:

String.Format("+{0:g}-{0:g}{1:g}-{1:g}j", real, imaginary)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top