I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like "2008-11-20T16:33:21Z"
to a DateTime
value. Numeric values like "42"
and "42.42"
must be converted to an Int32
value and a Double
value respectively.
What is the best and most efficient approach to detect if a string is an integer or a number? Are Int32.TryParse
or Double.TryParse
the way to go?
Checking If Given or Input String is Integer or Not Using isnumeric Function. Python's isnumeric() function can be used to test whether a string is an integer or not. The isnumeric() is a builtin function. It returns True if all the characters are numeric, otherwise False.
int isdigit( int arg ); Function isdigit() takes a single argument in the form of an integer and returns the value of type int . Even though, isdigit() takes integer as an argument, character is passed to the function. Internally, the character is converted to its ASCII value for the check.
Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.
Int.TryParse
and Double.TryParse
have the benefit of actually returning the number.
Something like Regex.IsMatch("^\d+$")
has the drawback that you still have to parse the string again to get the value out.
In terms of efficiency, yes, TryParse is generally the preferred route.
If you can know (for example, by reflection) the target type in advance - but don't want to have to use a big switch
block, you might be interested in using TypeConverter
- for example:
DateTime foo = new DateTime(2008, 11, 20);
TypeConverter converter = TypeDescriptor.GetConverter(foo);
string s = converter.ConvertToInvariantString(foo);
object val = converter.ConvertFromInvariantString(s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With