字符串格式显示 0 或 2 个小数位,而不是 1?

String format to display 0 or 2 decimal places, but not 1?

我想隐藏小数位,如果是0,或者显示2,如果有的话。

这可以用格式字符串来完成,还是我只需要做类似 .ToString("0.##") 的事情,然后编写代码在必要时添加一个额外的“0”?

为什么不创建一个为您做这件事的扩展程序呢?您可以稍后对其进行调整和优化,并且可以在任何地方访问并获得相同的结果,即使使用智能感知也是如此。

public static string ToSingleOrTwoDecimals(this double source)
{
    if (source % 1 == 0) {
        return ((int) source).ToString();
    }
    
    return source.ToString("#.##");
}

String.Format(...) 是专门为此制作的,并接受其中包含特殊标识符的字符串。 Microsoft Docs on String.Format(...)

// Using the standard 'F2' (two places after comma) format:
var myFormattedNumber1 = String.Format("{0:F2}", 1);      // 1.00
var myFormattedNumber2 = String.Format("{0:F2}", 1.05);   // 1.05
var myFormattedNumber3 = String.Format("{0:F2}", 1.50);   // 1.50

// We can see the subtle differences when overriding the standard 'F2' format:
var myFormattedNumber4 = String.Format("{0:#.##}", 1);     // 1
var myFormattedNumber5 = String.Format("{0:#.##}", 1.05);  // 1.05
var myFormattedNumber6 = String.Format("{0:#.##}", 1.50);  // 1.5

使用这个,你可以选择你的毒药。