c# - 什么是字符串格式 C# {0,12 :N0} (colon and commas) means?

标签 c#

好的,这是代码示例:

 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} 字符串格式参数后面的逗号是什么意思?

最佳答案

MSDN 文档是您的 friend (我在上面的评论中提供的链接也不是最好的链接):
Composite Formatting

Each format item takes the following form and consists of the following components: {index[,alignment][:formatString]}

所以 index 显然是提供的参数的索引:

String.Format("Second argument = {1}, first argument = {0}", arg1, arg2);

Alignment 指定所需的字段宽度和水平对齐方式:

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(例如 The Numeric ("N") Format Specifier)。

关于c# - 什么是字符串格式 C# {0,12 :N0} (colon and commas) means?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34940355/

相关文章:

c# - Visual Studio dll 创建故障排除

c# - system.serviceModel/bindings/wsHttpBinding 的绑定(bind)没有...错误

Javascript fromCharCode 在 C# 中等效

c# - 如何在 Mac OS 中注册服务?

c# - 将 UserControl 转换为特定类型的用户控件

c# - 需要有关 C# Twitch 机器人的帮助

c# - 我如何将 ActionLink "Add Pictures"放在导航栏的中间?

c# - 如何为 iPhone 制作聊天客户端

c# - SQLite 锁定文件,即使连接已关闭

c# - 通过 WCF 服务传递枚举