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

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


当前回答

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

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

其他回答

标准格式及其相关输出,

Console.WriteLine("Standard Numeric Format Specifiers");
String s = String.Format("(C) Currency: . . . . . . . . {0:C}\n" +
                    "(D) Decimal:. . . . . . . . . {0:D}\n" +
                    "(E) Scientific: . . . . . . . {1:E}\n" +
                    "(F) Fixed point:. . . . . . . {1:F}\n" +
                    "(G) General:. . . . . . . . . {0:G}\n" +
                    "    (default):. . . . . . . . {0} (default = 'G')\n" +
                    "(N) Number: . . . . . . . . . {0:N}\n" +
                    "(P) Percent:. . . . . . . . . {1:P}\n" +
                    "(R) Round-trip: . . . . . . . {1:R}\n" +
                    "(X) Hexadecimal:. . . . . . . {0:X}\n",
                    - 1234, -1234.565F);
Console.WriteLine(s);

示例输出(en-us文化):

(C) Currency: . . . . . . . . ($1,234.00)
(D) Decimal:. . . . . . . . . -1234
(E) Scientific: . . . . . . . -1.234565E+003
(F) Fixed point:. . . . . . . -1234.57
(G) General:. . . . . . . . . -1234
    (default):. . . . . . . . -1234 (default = 'G')
(N) Number: . . . . . . . . . -1,234.00
(P) Percent:. . . . . . . . . -123,456.50 %
(R) Round-trip: . . . . . . . -1234.565
(X) Hexadecimal:. . . . . . . FFFFFB2E

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

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

或者使用yourVariable

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

我不再担心文化和潜在的格式问题的方法是,我将其格式化为货币,然后去掉货币符号。

如果(小数。TryParse(tblCell, out result)

{
  formattedValue = result.ToString("C").Substring(1);
}
String.Format("0,###.###"); also works with decimal places
int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000