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

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


当前回答

标准格式及其相关输出,

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}"; 

如果你想要特定文化,你可能想试试这个:

使用命名空间:"using System.Globalization;"

(19950000.0)。ToString("N",new CultureInfo("en-US")) = 19,950,000.00

(19950000.0)。ToString("N",new CultureInfo("is-IS")) = 19.950.000,00

印度文化: (19950000.0)。ToString("N",new CultureInfo("hi-IN"))= 1,99,50,000.00

注意:一些区域性使用,表示小数而不是。所以要小心。

您可以使用这样的函数来格式化数字,并可选地传入所需的小数点后数位。如果没有指定小数点,它将使用两个小数点。

    public static string formatNumber(decimal valueIn=0, int decimalPlaces=2)
    {
        return string.Format("{0:n" + decimalPlaces.ToString() + "}", valueIn);
    }

我使用十进制,但你可以改变类型为任何其他或使用匿名对象。您还可以添加对负小数点值的错误检查。

就这么简单:

float num = 23658; // for example 
num = num.ToString("N0"); // Returns 23,658

更多信息在这里

如果您希望强制使用“,”分隔符,而不考虑区域性(例如在跟踪或日志消息中),那么下面的代码将可以工作,并且还有一个额外的好处,即告诉下一个偶然发现它的人您正在做什么。

int integerValue = 19400320; 
string formatted = string.Format(CultureInfo.InvariantCulture, "{0:N0}", integerValue);

设置格式为"19,400,320"