我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
当前回答
$"{1234:n}"; // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876
其他回答
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
如果您希望强制使用“,”分隔符,而不考虑区域性(例如在跟踪或日志消息中),那么下面的代码将可以工作,并且还有一个额外的好处,即告诉下一个偶然发现它的人您正在做什么。
int integerValue = 19400320;
string formatted = string.Format(CultureInfo.InvariantCulture, "{0:N0}", integerValue);
设置格式为"19,400,320"
您需要相同的格式值和特定于区域性。
Double value= 1234567;
value.ToString("#,#.##", CultureInfo.CreateSpecificCulture("hi-IN"));
输出:34567
更简单,使用字符串插值代替字符串。格式
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
或者使用yourVariable
double yourVariable = 12456.0;
$"{yourVariable:n0}";
$"{yourVariable:n2}";