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

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

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 

如果您想要完全符合该结果,则不能使用任何数值数据格式,因为不会将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 

您可以使用double的string.format或ToString方法来执行此操作。

 double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0; string MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero"); // In the US English culture, MyString has the value: $19.95. MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero"); // In the US English culture, MyString has the value: ($19.95). // The minus sign is omitted by default. MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero"); // In the US English culture, MyString has the value: Zero. 

如果您需要更多详细信息,msdn的这篇文章可以帮助您