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

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


当前回答

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

其他回答

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

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

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

输出:34567

例如String。格式(“{0时0}",1);返回01,对我来说无效

这对我很有用

19950000.ToString("#,#", CultureInfo.InvariantCulture));

输出 19950000年

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

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

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

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

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