在 C# 中格式化数字

Formatting a number in c#

我想用逗号分隔数字。我已经尝试了很多方法来做到这一点。但是没有用。

它已经转换为字符串,现在我想格式化 "tot"。

GetData getData = new GetData();
string tot = Convert.ToString(getData.Total_Extra(month));
string totVal = (tot).ToString("N",new CultureInfo("en-US"));
LB2.Text = tot.ToString();

您可以将 tot 字符串转换为数值,然后使用 string.Format 获得所需的格式:

string tot = "19950000";
string output = string.Format("{0:n2}", Convert.ToInt32(tot));
Debug.WriteLine(output); //19,950,000.00 on my machine

或者:

string output2 = Convert.ToInt32(tot).ToString("n2");

这些都是特定于文化的,因此在不同用户的机器上可能会显示不同(例如,印度文化将显示 1,99,50,000.00)。

如果您想强制 三位数逗号分组,那么您可以指定要使用的区域性:

string output2 = Convert.ToInt32(tot).ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
//19,950,000.00 on any machine

听起来你的 tot 可能不是一个数值,所以你应该在尝试格式化之前检查一下:

string tot = "19950000";
int totInt;
if (Int32.TryParse(tot, out totInt))
{
    string output = totInt.ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
    MessageBox.Show(output);
}
else
{
    MessageBox.Show("tot could not be parsed to an Int32");
}