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

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


当前回答

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

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

输出:34567

其他回答

$"{1234:n}";  // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876

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

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”

String.Format("0,###.###"); also works with decimal places
String.Format("{0:#,###,###.##}", MyNumber)

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

标准格式及其相关输出,

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