使用String.Format为数字和。添加逗号
使用String.Format我怎样才能确保所有数字在每3个数字后都有逗号,例如23000 =“23,000”,0返回“0”。
String.Format(“{0:n}”,0); //给出0.00我不想要的。 我不想要任何小数位,所有数字都是整数。
你可以做到这一点,我发现阅读意图更清晰:
String.Format("{0:#,###0}", 0);
例:
string.Format("{0:#,###0}", 123456789); // 123,456,789 string.Format("{0:#,###0}", 0); // 0
如果您当前的文化输入使用逗号作为千位分隔符,则可以将其格式化为零小数的数字:
String.Format("{0:N0}", 0)
要么:
0.ToString("N0")
来自msdn
double value = 1234567890; Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
显示1,234,567,890
如果没有其他解决方案适合您,您还可以使用CultureInfo对象玩一下:
var x = CultureInfo.CurrentCulture; x.NumberFormat.NumberDecimalSeparator = ","; x.NumberFormat.NumberDecimalDigits = 0; x.NumberFormat.NumberGroupSizes = new int[] {3};
您可以在N后面加上一个数字来指定小数位数:
String.Format("{0:n0}", 0) // gives 0
我向上标记了另一个答案,然后发现零值是一个空字符串。
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("de-DE"); System.Threading.Thread.CurrentThread.CurrentCulture = ci; double x = 23232323.21; string y = x.ToString("#,0", System.Globalization.CultureInfo.CurrentCulture);
该字符串在当前文化中返回,因此y = 23.232.323
当x = 0时,y = 0。
你就是这样说的:
Console.WriteLine(**$**"Your current amount of money is: **{yourVar:c}**");