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

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

其他回答

String.Format("0,###.###"); also works with decimal places

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

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

{
  formattedValue = result.ToString("C").Substring(1);
}

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

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
$"{1234:n}";  // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876
String.Format("{0:#,###,###.##}", MyNumber)

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