如果 int 包含 0,为什么在 int.ToString() 调用上指定格式化程序会导致空字符串?

Why does specifying a formatter on an int.ToString() call result in an empty string if the int contains 0?

这是一个非常简单的例子:

class Program
{
    static void Main(string[] args)
    {
        int val = 0;

        Console.WriteLine(val.ToString());      // outputs: "0"
        Console.WriteLine(val.ToString("#,#")); // outputs: "" <-- what if I want "0"!?!?

        val = 1;

        Console.WriteLine(val.ToString());      // outputs: "1"
        Console.WriteLine(val.ToString("#,#")); // outputs: "1"

        Console.Read();
    }
}

有一种情况,我有一个包含 0 值的 int。我希望它显示为“0”,但它显示为空字符串。是因为 0 是 int 的默认值吗?格式化程序是否假设因为它是默认输出应该是“”?

如果你想要0,使用#,0

#表示可选 0表示强制

您可以在这里阅读更多内容:Custom Numeric Format Strings

The digit placeholder (#) is similar to the zero placeholder. It defines the position of a digit within the resultant formatted string and causes rounding after the decimal point. However, the digit placeholder does not cause leading or trailing zeroes to be added to a number where the original numeric value has no digit in the appropriate position. The digit placeholder has a side effect when converted a zero value to a string. As the placeholder will not cause the creation of either leading or trailing zeroes, when converting a zero value the resultant string is empty.

C# Number to String Conversion