我有一个数字,小数点后的位数是可变的。我想用逗号和所有小数来格式化这个数字。
例如:42,023,212.0092343234
如果我使用 ToString("N") ,我只能得到 2 个小数,而 ToString("f") 可以给我所有的小数但没有逗号。那么我该如何同时得到逗号和所有小数呢?
我不确定(现在也无法测试),但是这样的东西会起作用吗?
"#,##0.################"
string.Format("{0:#,##0.############}", value);
该值将提供高达12位小数。
没有一个自定义格式说明符可以表示“所有后续数字”,因此类似于这样的内容最接近您想要的。
请注意,您的变量精度受限。双精度只有15-16位有效数字,因此当左侧变得更大时,小数位数将减少。
默认情况下,Double值包含15个小数位精度,尽管内部维护了最大17个数字。
因此,我认为pdr的做法是正确的。只需执行以下操作:
// As long as you've got at least 15 #s after the decimal point,
// you should be good.
value.ToString("#,#.###############");
static string Format(double value)
{
double wholePart = Math.Truncate(value);
double decimalPart = Math.Abs(value - wholePart);
return wholePart.ToString("N0") + decimalPart.ToString().TrimStart('0');
}
例子:
Console.WriteLine(Format(42023212.0092343234));
输出:
42,023,212.00923432409763336
哈,你看,这个结果并不完美,可能是由于浮点数计算问题所致。无论如何,这是一种选择。
我们来试试这个
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
尝试使用 ToString("N2")
以下是一种方法,可以稍微满足您的期望...
decimal d = 42023212.0092343234M;
NumberFormatInfo nfi = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberDecimalDigits= (d - Decimal.Truncate(d)).ToString().Length-2;
Console.WriteLine(d.ToString("N",nfi));
关于NumberFormatInfo的更多详细信息,请查看MSDN。
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx