我有一个小数点后可变位数的数字 . 我想用逗号和所有十进制数格式化数字 .
例如:42,023,212.0092343234
如果我使用ToString(“N”)我只得到2位小数,ToString(“f”)给我所有小数都没有逗号 . 我如何得到两者?
不确定(现在无法测试)但是这样的工作会怎么样?
"#,##0.################"
string.Format("{0:#,##0.############}", value);
最多可以给你12位小数 .
“所有后续数字”没有自定义格式说明符,因此这样的内容最接近您想要的内容 .
另请注意,您受变量精度的限制 . A double 只有15-16位精度,所以当你的左手边变大时,小数位数会下降 .
double
UPDATE :看着MSDN documentation on the System.Double type,我看到了这个:
默认情况下,Double值包含15个十进制数字的精度,但内部最多保留17位数 .
所以我认为pdr's on to something,实际上 . 这样做:
// 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
哈,嗯,正如你所看到的,由于(我认为)浮点数学问题,这给出了不完美的结果 . 那好吧;无论如何,这是一个选择 .
试试 ToString("N2")
ToString("N2")
我们来试试吧
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
这是达到你期望的方式......
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
6 回答
不确定(现在无法测试)但是这样的工作会怎么样?
最多可以给你12位小数 .
“所有后续数字”没有自定义格式说明符,因此这样的内容最接近您想要的内容 .
另请注意,您受变量精度的限制 . A
double
只有15-16位精度,所以当你的左手边变大时,小数位数会下降 .UPDATE :看着MSDN documentation on the System.Double type,我看到了这个:
所以我认为pdr's on to something,实际上 . 这样做:
这是一个想法:
例:
输出:
哈,嗯,正如你所看到的,由于(我认为)浮点数学问题,这给出了不完美的结果 . 那好吧;无论如何,这是一个选择 .
试试
ToString("N2")
我们来试试吧
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
这是达到你期望的方式......
有关NumberFormatInfo的更多详细信息..请查看MSDN ..
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx