我想在一个数字的千位上加一个逗号。

String.Format()是正确的路径吗?我应该使用什么格式?


当前回答

int num = 98765432;
Console.WriteLine(string.Format("{0:#,#}", num));

其他回答

更简单,使用字符串插值代替字符串。格式

 $"{12456:n0}"; // 12,456
 $"{12456:n2}"; // 12,456.00

或者使用yourVariable

 double yourVariable = 12456.0;
 $"{yourVariable:n0}"; 
 $"{yourVariable:n2}"; 

这是最好的格式。适用于所有这些情况:

String.Format( "{0:#,##0.##}", 0 ); // 0
String.Format( "{0:#,##0.##}", 0.5 ); // 0.5 - some of the formats above fail here. 
String.Format( "{0:#,##0.##}", 12314 ); // 12,314
String.Format( "{0:#,##0.##}", 12314.23123 ); // 12,314.23
String.Format( "{0:#,##0.##}", 12314.2 ); // 12,314.2
String.Format( "{0:#,##0.##}", 1231412314.2 ); // 1,231,412,314.2

您需要相同的格式值和特定于区域性。

 Double value= 1234567;
 value.ToString("#,#.##", CultureInfo.CreateSpecificCulture("hi-IN"));

输出:34567

投票最多的答案很好,7年来一直很有帮助。随着c# 6.0的引入,特别是字符串插值,有了一种更整洁,在我看来更安全的方法来完成要求在数字的千位处添加逗号:

var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal

其中变量i被放置在占位符(即{0})的位置。所以不需要记住哪个物体到哪个位置。格式(即:n)没有改变。要了解最新的完整功能,您可以访问这个页面。

String.Format("{0:#,###,###.##}", MyNumber)

这将在相关点处给出逗号。