【问题标题】:Formatting a number in c#在c#中格式化数字
【发布时间】:2016-08-04 09:02:37
【问题描述】:

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

它已经转换为字符串,现在我想格式化“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();

【问题讨论】:

  • 您的实际和预期输出是什么?
  • 我希望标签中的值显示为 19,950,000.00
  • 您应该展示您尝试过的代码以及“无效”的含义
  • 在您最近的编辑中,不应该是LB2.Text = totVal; 吗?

标签: c# .net string formatting cultureinfo


【解决方案1】:

您可以将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");
}

【讨论】:

  • 我也试过了但是会产生异常。我已经上传了当前代码,请看一下。
  • GetData getData = new GetData();字符串 tot = Convert.ToString(getData.Total_Extra(month)); string totVal = string.Format("0:n2", Convert.ToInt32(tot)); LB2.Text = totVal.ToString();
  • 你已经尝试过浮动,但我想格式化字符串值
  • Matt Wilko - 我试过带和不带花括号。我收到异常说输入类型错误
  • @MattWilko :伙计,这是您在答案中输入的代码,我只想说我已经尝试过您的代码并且工作正常。 OP的截图:)
猜你喜欢
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多