Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int.TryParse not working

Tags:

c#

asp.net

My code is like this

string asd = "24000.0000";
int num2;
if (int.TryParse(asd, out num2))
{

    // It was assigned.
}

Now code execution never enters to if case, that means try parse is not working. Can any one tell me whats wrong with the code.

Note:In first step The value 24000.0000 is purposefully assigned as string .

like image 835
None Avatar asked Jul 22 '13 13:07

None


2 Answers

Use the second TryParse overload that allows you to specify NumberStyle parameters to allow for decimals.

int val =0;
var parsed = int.TryParse("24000.0000", 
                NumberStyles.Number, 
                CultureInfo.CurrentCulture.NumberFormat, 
                out val);
like image 50
asawyer Avatar answered Sep 19 '22 14:09

asawyer


For an int, you cannot have decimal places.

EDIT:

string asd = "24000.000";

int dotPos = asd.LastIndexOf('.');

if (dotPos > -1) {
   asd = asd.Substring(0, dotPos);
} 

int num2;

if (int.TryParse(asd, out num2))
{
 // It was assigned.
}

EDIT:

As pointed out by other answers, there are better ways to deal with the conversion.

like image 20
Jason Evans Avatar answered Sep 18 '22 14:09

Jason Evans