int.TryParse()为"#.##"返回false

Sun*_*nil 15 c# tryparse

我有一个接收字符串参数并将它们转换为整数的函数.
为了安全转换,使用int.TryParse().

public IEnumerable<object> ReportView(string param1, string param2)
{
  int storeId = int.TryParse(param1, out storeId) ? storeId : 0;
  int titleId = int.TryParse(param2, out titleId) ? titleId : 0;
  IEnumerable<object> detailView = new Report().GetData(storeId, titleId);
  return detailView;
}
Run Code Online (Sandbox Code Playgroud)

函数调用ReportView("2","4") - > int.Tryparse成功解析数字
函数调用ReportView("2.00","4.00") - > int.TryParse无法解析数字

为什么?任何的想法?

@Update
对不起,伙计们,我的观念错了.我是c#的新手,我以为Int.TryParse()将返回整数部分并忽略小数.但它不会,甚至Convert.ToInt32("字符串")
感谢所有.

Mik*_*tts 6

int.TryParse不会尝试解析字符串并将其转换为整数以防万一.您需要使用decimal.TryParse作为十进制数字字符串.


小智 6

public IEnumerable<object> ReportView(string param1, string param2)
{
  decimal tmp;
  int storeId = decimal.TryParse(param1, out tmp) ? (int)tmp : 0;
  int titleId = decimal.TryParse(param2, out tmp) ? (int)tmp : 0;
  IEnumerable<object> detailView = new Report().GetData(storeId, titleId);
  return detailView;
}
Run Code Online (Sandbox Code Playgroud)

以上将适用于Integer或Decimal字符串.请注意,"2.123"形式的字符串将导致返回2的Integer值.


Joe*_*orn 5

2.00 和 4.00 不是整数;它们是十进制值,只是小数点后恰好有 0。如果要解析小数,请使用decimal.TryParse() 或double.TryParse(),然后截断它们或检查零值尾数。


ihe*_*arp 5

对于计算机来说,“2.00”是浮点数/小数,而不是整数。您可以通过删除尾随零来预处理字符串,然后执行 int.TryParse(),而不是执行decimal.TryParse()。因此,如果您有“2.00”,您将继续检查(并删除)字符串的最后一个字符,直到到达“.”。(十进制)。如果是“0”或“.” 你可以放弃它。最后你只会得到“2”。