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

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


当前回答

投票最多的答案很好,7年来一直很有帮助。随着c# 6.0的引入,特别是字符串插值,有了一种更整洁,在我看来更安全的方法来完成要求在数字的千位处添加逗号:

var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal

其中变量i被放置在占位符(即{0})的位置。所以不需要记住哪个物体到哪个位置。格式(即:n)没有改变。要了解最新的完整功能,您可以访问这个页面。

其他回答

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

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

试试这个:

var number = 123456789;
var str = number.ToString("N0");

结果是:“123,456,789”

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

这对我很有用

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

输出 19950000年

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

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

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

投票最多的答案很好,7年来一直很有帮助。随着c# 6.0的引入,特别是字符串插值,有了一种更整洁,在我看来更安全的方法来完成要求在数字的千位处添加逗号:

var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal

其中变量i被放置在占位符(即{0})的位置。所以不需要记住哪个物体到哪个位置。格式(即:n)没有改变。要了解最新的完整功能,您可以访问这个页面。