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

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


当前回答

下面的示例显示了使用包含零占位符的自定义格式字符串格式化的几个值。

String.Format("{0:N1}", 29255.0);

Or

29255.0.ToString("N1")

结果“29255 .0

String.Format("{0:N2}", 29255.0);

Or

29255.0.ToString("N2")

结果“29255”

其他回答

int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

标准格式及其相关输出,

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

投票最多的答案很好,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)没有改变。要了解最新的完整功能,您可以访问这个页面。

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

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

{
  formattedValue = result.ToString("C").Substring(1);
}
String.Format("0,###.###"); also works with decimal places