我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
我想在一个数字的千位上加一个逗号。
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:#,##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:##,###.00}", myValue)
但是当你有像0.2014这样的值时,它会失败,因为我使用。21
string.Format("{0:#,##0.00}", myValue)
您可以使用这样的函数来格式化数字,并可选地传入所需的小数点后数位。如果没有指定小数点,它将使用两个小数点。
public static string formatNumber(decimal valueIn=0, int decimalPlaces=2)
{
return string.Format("{0:n" + decimalPlaces.ToString() + "}", valueIn);
}
我使用十进制,但你可以改变类型为任何其他或使用匿名对象。您还可以添加对负小数点值的错误检查。
int num = 98765432;
Console.WriteLine(string.Format("{0:#,#}", num));