遗憾的是,MSDN文档对此并不十分清楚。我想知道以下数字格式化程序之间有什么区别。
#,#
#,0
#,#0
#,##0
#,###0
(不确定这是否有效,因为我目前无法测试)
据我所知,他们都会将12345
等数字格式化为12,345
。当然,在某些情况下会有一些微妙的差异吗?
最后,#,#
或#,0
左侧是否有任何带有说明符的有效格式字符串?如果是这样,他们做了什么?
答案 0 :(得分:1)
似乎与(3)存在差异。
这是我敲响的代码:
static void Main(string[] args)
{
string[] arrFormat = new string[] { "{0:#,0}", "{0:#,#0}", "{0:#,##}", "{0:#,###0}" };
int[] ints = new int[] {0, 1, 10, 19, 100, 123, 1234, 12345};
double[] doubles = new double[]{ 0, 0.1, 1.1, 10.12, 100.1, 123.45,
12334.4567, 1234.56, 12345.6};
foreach (string specifier in arrFormat)
{
Console.Write(specifier + ":\t\t" );
foreach (int i in ints)
{
Console.Write(string.Format(specifier, i) + ", ");
}
Console.WriteLine("");
}
Console.WriteLine("-------------------------------------------");
foreach (string specifier in arrFormat)
{
Console.Write(specifier + ":\t\t");
foreach (double d in doubles)
{
Console.Write(string.Format(specifier, d) + ", ");
}
Console.WriteLine("");
}
}
这是输出:
{0:#,0}: 0, 1, 10, 19, 100, 123, 1,234, 12,345,
{0:#,#0}: 0, 1, 10, 19, 100, 123, 1,234, 12,345,
{0:#,##}: , 1, 10, 19, 100, 123, 1,234, 12,345,
{0:#,###0}: 0, 1, 10, 19, 100, 123, 1,234, 12,345,
-------------------------------------------
{0:#,0}: 0, 0, 1, 10, 100, 123, 12,334, 1,235, 12,346,
{0:#,#0}: 0, 0, 1, 10, 100, 123, 12,334, 1,235, 12,346,
{0:#,##}: , , 1, 10, 100, 123, 12,334, 1,235, 12,346,
{0:#,###0}: 0, 0, 1, 10, 100, 123, 12,334, 1,235, 12,346,
[如果有人想改进测试用例,请随意。]
SteveX的文章是格式字符串的一个很好的参考:String Formatting in C#