Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a string is a number in C#

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?

like image 428
Lars Fastrup Avatar asked Nov 20 '08 15:11

Lars Fastrup


People also ask

How do you know if its string or integer?

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.

How do you check if an element is an integer in C?

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.

How do you know if input is a number?

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.


2 Answers

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.

like image 58
kͩeͣmͮpͥ ͩ Avatar answered Oct 01 '22 03:10

kͩeͣmͮpͥ ͩ


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);
like image 40
Marc Gravell Avatar answered Oct 01 '22 03:10

Marc Gravell