Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

tryparse

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.

like image 988
Sunil Avatar asked Apr 04 '12 14:04

Sunil


People also ask

What does int TryParse return?

TryParse is a static data conversion method that allows to convert a string value to a corresponding 32-bit signed integer value. It returns a Boolean True value for successful conversion and False in case of failed conversion.

How does TryParse int work?

TryParse(String, NumberStyles, IFormatProvider, Int32) Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What does TryParse return if successful?

6 Answers. Show activity on this post. No, TryParse returns true or false to indicate success. The value of the out parameter is used for the parsed value, or 0 on failure.

What is TryParse used for?

TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.


1 Answers

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.

like image 192
ethang Avatar answered Oct 23 '22 10:10

ethang