c# - 使用字符串插值将字符串格式化为列

标签 c# string format double c#-6.0

我需要打印 double ,以便为值的字符串表示分配一定数量的符号(如 8)。接下来的单词应该从每个字符串中字符串开头的相同索引开始。现在我有:

value: 0 test
value: 0.3333333333333 test
value: 0.5 test

我需要:

value: 0           test
value: 0.33333333  test
value: 0.5         test

测试代码:

double[] ar = new double[] { 0, (double)1 / 3, (double)1 / 2 };
string s = "test";

foreach (var d in ar)
{
    Console.WriteLine($"value: {d} {s}");
}

我应该在 {d: 之后添加什么?

最佳答案

您可以使用 Alignment Component以此目的。像这样:

Console.WriteLine($"value: {d,-17} {s}");

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

这就是我们使用负对齐的原因,因为您希望第一列左对齐

关于c# - 使用字符串插值将字符串格式化为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44427194/

相关文章:

css - 如何调整 MediaWiki 列表项之间的间距?

c# - 将一个数组与另一个数组进行匹配

c# - Fluent NHibernate Reveal 不使用给定的属性名

c# - Unity 增加一个值然后减少它(DayNightCycle)

C# 日期时间到 W3CDTF

delphi - 按地区禁用格式源

c# - 在 C# 中清除或检查事件处理程序

javascript - 如何在忽略空格的情况下匹配另一个字符串中的字符串

java - 为什么会出现这些重复案例?

java - 将 json 字符串转换为 java arraylist(使用 jackson)