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

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


当前回答

int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

其他回答

如果你想在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,###.###"); also works with decimal places

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

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

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

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

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”

String.Format("{0:#,###,###.##}", MyNumber)

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