字符串格式C#{0,12:N0}(冒号和逗号)的含义是什么? [英] What is String Format C# {0,12:N0} (colon and commas) means?
问题描述
好的,下面是代码示例:
Okay here's the code example:
string header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
"City", "Year", "Population", "Change (%)");
Console.WriteLine(header);
string output;
foreach (var city in cities) {
output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3)/ (double)city.Item3);
Console.WriteLine(output);
}
}
}
// The example displays the following output:
// City Year Population Year Population Change (%)
//
// Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
// New York 1940 7,454,995 1950 7,891,957 5.9 %
// Chicago 1940 3,396,808 1950 3,620,962 6.6 %
// Detroit 1940 1,623,452 1950 1,849,568 13.9 %
我理解args {0:N0}表示无小数点后的冒号,但是昏迷呢?像{0,-12}和{1,12}一样,在字符串格式的参数之后逗号是什么意思?
i understand about the colon after the args {0:N0} means no decimal, but what about the comas? like {0,-12}, and {1,12} what does comma means after the argument of the string format?
推荐答案
MSDN文档是您的朋友(我在上面的评论中给出的链接也不是最好的):
复合格式
MSDN Documentation is your friend (the link I gave in comments above wasn't the best either):
Composite Formatting
每个格式项都需要格式,由以下部分组成:
{index [,alignment] [:formatString]}
Each format item takes the following form and consists of the following components: {index[,alignment][:formatString]}
因此 index
显然是所提供参数的索引:
So the index
is obviously the index of the provided arguments:
String.Format("Second argument = {1}, first argument = {0}", arg1, arg2);
对齐方式
指定所需的字段宽度和水平对齐方式:
Alignment
specifies the desired width of the field and horizontal alignment:
如果对齐方式为正,则字段中的格式化数据为右对齐,如果对齐方式为负,则为左对齐。 / p>
The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative.
String.Format("{0,-12}" + // first argument, left align, 12 character wide column
"{1,8:yyyy}" + // second argument, right align, 8 character wide column,
// formatted as a year
"{2,12:N0}" + // third argument, right align, 12 character wide column,
// formatted as a number, 0 decimal places
和您已经知道的 formatString
(例如数字( N)格式说明符)。
And formatString
you already know about (e.g. The Numeric ("N") Format Specifier).
这篇关于字符串格式C#{0,12:N0}(冒号和逗号)的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!