int.TryParse() returns false for "#.##"

Sunil picture Sunil · Apr 4, 2012 · Viewed 14k times · Source

I'm having a function which receives string parameters and convert them to integers.
For safe conversion int.TryParse() is used.

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;
}

Function call ReportView(“2”,”4”)--> int.Tryparse successfully parsing the numbers
Function call ReportView(“2.00”,”4.00”) --> int.TryParse fails to parse the numbers

Why? Any idea?

@Update
Sorry guys, my concept was wrong. I'm new to c#, I thought Int.TryParse() would return integral part and ignore the decimals. But it won't, even Convert.ToInt32("string")
Thanks to all.

Answer

ethang picture ethang · Apr 4, 2012
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;
}

The above will work with Integer or Decimal strings. Mind you that strings of the form "2.123" will result in the Integer value of 2 being returned.