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

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


当前回答

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

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

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

其他回答

更简单,使用字符串插值代替字符串。格式

 $"{12456:n0}"; // 12,456
 $"{12456:n2}"; // 12,456.00

或者使用yourVariable

 double yourVariable = 12456.0;
 $"{yourVariable:n0}"; 
 $"{yourVariable:n2}"; 
String.Format("{0:#,###,###.##}", MyNumber)

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

如果你想在DataGridview中显示它,你应该改变它的类型,因为默认是字符串,因为你把它改变为十进制,它认为是数字与浮点数

Dim dt As DataTable = New DataTable
dt.Columns.Add("col1", GetType(Decimal))
dt.Rows.Add(1)
dt.Rows.Add(10)
dt.Rows.Add(2)

DataGridView1.DataSource = dt

下面的示例显示了使用包含零占位符的自定义格式字符串格式化的几个值。

String.Format("{0:N1}", 29255.0);

Or

29255.0.ToString("N1")

结果“29255 .0

String.Format("{0:N2}", 29255.0);

Or

29255.0.ToString("N2")

结果“29255”

c# 7.1(也许更早?)通过字符串插值使这变得简单而美观:

var jackpot = 1_000_000; // underscore separators in numeric literals also available since C# 7.0
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";