C#双重格式对齐十进制符号

Paa*_*and 6 c# double formatting

我将数字与不同的小数位对齐,以便小数符号在直线上对齐.这可以通过填充空格来实现,但我遇到了麻烦.

Lays说我想对齐以下数字:0 0.0002 0.531 2.42 12.5 123.0 123172

这是我追求的结果:

     0
     0.0002
     0.531
     2.42
    12.5
   123.0
123172
Run Code Online (Sandbox Code Playgroud)

Guf*_*ffa 6

如果您想要完全符合该结果,则不能使用任何格式的数字数据,因为它不会格式化123123.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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

     0
     0.0002
     0.531
     2.42
    12.5
   123.0
123172
Run Code Online (Sandbox Code Playgroud)