我将数字与不同的小数位数对齐,以便小数点符号对齐在一条直线上。这可以通过用空格填充来实现,但我遇到了麻烦。
外行说我想对齐以下数字: 0 0.0002 0.531 2.42 12.5 123.0 123172
这是我想要的结果:
0
0.0002
0.531
2.42
12.5
123.0
123172
最佳答案
如果您确实想要那个结果,则不能使用任何格式的数字数据,因为那样不会将 123
格式化为 123.0
。您必须将这些值视为字符串以保留尾随零。
这会为您提供您所要求的结果:
string[] numbers = { "0", "0.0002", "0.531", "2.42", "12.5", "123.0", "123172" };
foreach (string number in numbers)
{
int pos = number.IndexOf('.');
if (pos == -1)
pos = number.Length;
Console.WriteLine(new String(' ', 6 - pos) + number);
}
输出:
0
0.0002
0.531
2.42
12.5
123.0
123172
关于C# 双格式对齐小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2332912/