![](/img/trans.png)
[英]C# Double - ToString formatting to show a value in cents with no decimal displayed
[英]C# double formatting align on decimal sign
我将数字与各种小数位数对齐,以便小数点符号对齐在一条直线上。 这可以通过填充空格来实现,但我遇到了麻烦。
俗话说我想对齐以下数字: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
虽然由于尾随零而不能完全回答问题,但这会将小数点与 4 个小数位对齐,总共最多 11 个字符。
someNumber.ToString("0.0000").PadLeft(11)
例如。 以下字符串
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)
是
0.0000
0.0002
0.5310
2.4200
12.5000
123.0000
123172.0000
在不变的文化中。
您可以使用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.
如果您需要更多详细信息,msdn的这篇文章可以帮助您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.