What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use Double.Parse
or a regex (see below) but I was wondering if there is some built in way to do this, such as javascript's NaN()
or IsNumeric()
(was that VB, I can't remember?).
public static bool IsNumeric(this string value) { return Regex.IsMatch(value, "^\\d+$"); }
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.
C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.
I prefer something like this, it lets you decide what NumberStyle
to test for.
public static Boolean IsNumeric(String input, NumberStyles numberStyle) { Double temp; Boolean result = Double.TryParse(input, numberStyle, CultureInfo.CurrentCulture, out temp); return result; }
This doesn't have the regex overhead
double myNum = 0; String testVar = "Not A Number"; if (Double.TryParse(testVar, out myNum)) { // it is a number } else { // it is not a number }
Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.
update
secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.
example 1:
public Boolean IsNumber(String s) { Boolean value = true; foreach(Char c in s.ToCharArray()) { value = value && Char.IsDigit(c); } return value; }
or if you want to be a little more fancy
public Boolean IsNumber(String value) { return value.All(Char.IsDigit); }
update 2 ( from @stackonfire to deal with null or empty strings)
public Boolean IsNumber(String s) { Boolean value = true; if (s == String.Empty || s == null) { value=false; } else { foreach(Char c in s.ToCharArray()) { value = value && Char.IsDigit(c); } } return value; }
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