mousemat24
asked on
How to check if a value is a integer.
Hi there
Wonder if you can help me?
Im pulling out some information from a SQL table, one of the fields in SQL may contain an integer or char's or alpha numeric.
so
I could have
12 or testing or testing123 or testing 123
How do I check if the value is an integer? So the code will do something if its 12 but do something else if its testing 123 or testing123 or testing.
hope that makes sense?
Mousemat24
Wonder if you can help me?
Im pulling out some information from a SQL table, one of the fields in SQL may contain an integer or char's or alpha numeric.
so
I could have
12 or testing or testing123 or testing 123
How do I check if the value is an integer? So the code will do something if its 12 but do something else if its testing 123 or testing123 or testing.
hope that makes sense?
Mousemat24
Or you can create a custom IsNumeric function, that will loop through all chars and use char method isDigit to check if it is numeric.
Goran
Goran
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Throwing an exception is the last option, since it is much slower that using int32.TryParse
Goran
Goran
goran, are you addressing to me? if yes, where do you see exception throwing?
that's an exception throwing:
throw new Exception( "my exception message" );
but TryParse does indeed looks more elegant and it's less coding.
cheers,
yurich
that's an exception throwing:
throw new Exception( "my exception message" );
but TryParse does indeed looks more elegant and it's less coding.
cheers,
yurich
sorry, it's indeed. disregard first three sentences of my previous post.
ASKER
Hi there, you've lost me now, should I use
private bool IsNumber( string str )
{
try
{
int x = Convert.ToInt32( str );
return true;
}
catch
{
return false;
}
}
or not? You say I should use TryParse, can you please send me some code please?
Many thanks for helping me out
Mousemat24
private bool IsNumber( string str )
{
try
{
int x = Convert.ToInt32( str );
return true;
}
catch
{
return false;
}
}
or not? You say I should use TryParse, can you please send me some code please?
Many thanks for helping me out
Mousemat24
see this link
http://www.codeproject.com/useritems/IsNumeric.asp
http://www.codeproject.com/useritems/IsNumeric.asp
You can use try-catch combo, but more elegant way would be:
private bool IsNumber( string str )
{
int result = Int32.MinValue;
return ( Int32.TryParse( str, result ) == null ) ? false : true;
}
Cheers,
Yurich
private bool IsNumber( string str )
{
int result = Int32.MinValue;
return ( Int32.TryParse( str, result ) == null ) ? false : true;
}
Cheers,
Yurich
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks guys for helping out!! :-)
pleasure :)
Goran