我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
当前回答
更简单,使用字符串插值代替字符串。格式
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
或者使用yourVariable
double yourVariable = 12456.0;
$"{yourVariable:n0}";
$"{yourVariable:n2}";
其他回答
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}";
$"{1234:n}"; // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876
我发现这是最简单的方法:
myInteger.ToString("N0")
如果你想在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
就这么简单:
float num = 23658; // for example
num = num.ToString("N0"); // Returns 23,658
更多信息在这里