views:

86

answers:

2

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"

A: 

This is probably way off...

How about something like:

String.Format("+{0:g}-{0:g}{1:g}-{1:g}j", real, imaginary)
NitroxDM
+1  A: 

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.

Hans Passant
Tweaked as follows, this'll do. re.ToString("G")+(im.CompareTo(0.0) >= 0 ? "+" : "") + im.ToString("G")+"j";
Max Yaffe