gpt4 book ai didi

c# - 在 .Net String.Format 中强制加倍为正号

转载 作者:行者123 更新时间:2023-11-30 22:46:34 28 4
gpt4 key购买 nike

上下文:.Net、C#

我想打印一个由两个 double 组成的复数。符号需要显示在虚部。我想为每个部分使用默认的双重格式,以尽量减少字符数。

我尝试使用 String.Format("{0:+G;-G}{1:+G;-G}j", real, imaginary) 但这最终打印:"+G-Gj"。不是我想要的。

有没有什么方法可以使用 G 说明符来做到这一点,或者我是否需要做一个会牺牲自动切换指数的自定义格式,例如{1:+#.######e###;-#.######e###}j"

最佳答案

这很不寻常,但您可以轻松地覆盖 Complex 类的 ToString 方法。例如:

  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);
}
}

示例用法:

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

输出:

  +1.00i-1.00

根据需要进行调整。

关于c# - 在 .Net String.Format 中强制加倍为正号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2588592/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com