[英]C# double formatting align on decimal sign
I align numbers with various number of decimals so that the decimal sign aligns on a straight row.我将数字与各种小数位数对齐,以便小数点符号对齐在一条直线上。 This can be achevied by padding with spaces, but I'm having trouble.
这可以通过填充空格来实现,但我遇到了麻烦。
Lays say I want to align the following numbers: 0 0.0002 0.531 2.42 12.5 123.0 123172俗话说我想对齐以下数字:0 0.0002 0.531 2.42 12.5 123.0 123172
This is the result I'm after:这是我追求的结果:
0
0.0002
0.531
2.42
12.5
123.0
123172
If you want exactly that result you can't use any formatting of numerical data, as that would not format 123
as 123.0
. 如果您想要完全符合该结果,则不能使用任何数值数据格式,因为不会将
123
格式化为123.0
。 You have to treat the values as strings to preserve the trailing zero. 您必须将值视为字符串以保留尾随零。
This gives you exactly the result that you asked for: 这为您提供了您要求的结果:
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);
}
Output: 输出:
0
0.0002
0.531
2.42
12.5
123.0
123172
While not exactly answering the question because of the trailing zeros, this aligns decimal points with 4 decimal places and a maximum of 11 characters in total.虽然由于尾随零而不能完全回答问题,但这会将小数点与 4 个小数位对齐,总共最多 11 个字符。
someNumber.ToString("0.0000").PadLeft(11)
Eg.例如。 the following strings
以下字符串
0d.ToString("0.0000").PadLeft(11)
0.0002d.ToString("0.0000").PadLeft(11)
0.531d.ToString("0.0000").PadLeft(11)
2.42d.ToString("0.0000").PadLeft(11)
12.5d.ToString("0.0000").PadLeft(11)
123.0d.ToString("0.0000").PadLeft(11)
123172d.ToString("0.0000").PadLeft(11)
are是
0.0000
0.0002
0.5310
2.4200
12.5000
123.0000
123172.0000
in the invariant culture.在不变的文化中。
You can use string.format or ToString method of double to do so. 您可以使用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 U.S. English culture, MyString has the value: $19.95.
MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero");
// In the U.S. 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 U.S. English culture, MyString has the value: Zero.
this article from msdn can help you if you need more details 如果您需要更多详细信息,msdn的这篇文章可以帮助您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.