【问题标题】:C# Convert back from thousand separator to intC#将千位分隔符转换回int
【发布时间】:2020-11-27 20:45:23
【问题描述】:

我有一个将 int 设置为 thousend 分隔符的代码,但是当我尝试将文本框中的这个值保存到数据库时,我想删除它们之间的空格。我无法用 replace(" ","") 做到这一点。

YearTB.Text = (String.Format(culture, "{0:n0}", Int32.Parse(YearTB.Text)));

方框中的内容例如是“536 396”,但中间的空格不是“”。它是千位分隔符的效果。我怎样才能将它返回到 int. “536396”。

【问题讨论】:

  • 这必须是控件将其转换为数字类型的责任,它知道执行此类转换所需的所有信息。
  • 您要转换的确切值是多少?
  • 如果这是一种已知文化的格式,则使用该文化解析字符串,然后使用与数据库格式匹配的文化写入它

标签: c#


【解决方案1】:

如果您只想转换为没有千位的字符串而不是 int:

string result = text.Replace(culture.NumberFormat.NumberGroupSeparator, "");

这假定cultureCultureInfo,使用千位分隔符格式化数字。

或者,如果您想转换为 int,您可以直接使用 int.Parse() 并指定您要允许千位分隔符(我认为这是一种更好的方法):

int result = int.Parse(text, NumberStyles.AllowThousands, culture);

【讨论】:

  • int result = int.Parse(text, NumberStyles.AllowThousands);就够了。我的 GridViewChargeTime.UpdateRow(r.RowIndex, false); 的一个问题无法保存到数据库,因为文本框仍然是千位格式。
【解决方案2】:

试试这个

string str = "536 396";
str = Regex.Replace(str, @"\s", "");

【讨论】:

    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 2015-07-12
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多