Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

int.TryParse will not try to parse the string and convert it to an integer just in case. You need to use decimal.TryParse for a decimal number string.

2.00 and 4.00 aren't integers. If you want to parse decimals, use decimal.TryParse() or double.TryParse(), and then truncate them or check for a zero-value mantissa.

To a computer "2.00" is a float/decimal, not an integer. Instead of doing decimal.TryParse() you can pre-process the string by removing the trailing zeros and then do int.TryParse(). So if you have "2.00", you keep checking (and dropping) the last character of the string until you reach the "." (decimal). If it is "0" or "." you can drop it. In the end you will end up with just "2".

2.00 and 4.00 are not of Integer data types - that's why. If you want those to be true try, double.TryParse() or decimal.TryParse()

well 2.00 is a decimal number, not an int in a computers eyes.

It fails to parse because decimal numbers are not integers.

Because "2.00" is a decimal, not an integer.

An Int32 (int) can only contain integral values; therefore the Int32 Parse/TryParse functions cannot parse strings with decimals. If your string values might contain decimals but are intended to represent integers, use Decimal.TryParse and then cast.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top