Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - Formatting a string into columns using String Interpolation

I need to print doubles so that definite number of symbols (like 8) is allocated for string representation of value. Next words should start at same index from beginning of string in each string. Now I have:

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

I need:

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

Test code:

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

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

What should I add after {d:?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Alignment Component for this purpose. Like this:

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.

So this is why we use negative alignment because you want the first column be left-aligned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...