I have been a Visual Basic programmer for the last ten years. I truly enjoy writing in this language. However, I also write software in C#. One of the things I have noticed that is missing from C# is a simple routine that tells me if a value is a number. Of course I could reference the Microsoft.VisualBasic namespace. Since I don’t want to be ostracized by the C# community I created a C# IsNumeric function using a regular expression instead.
The IsNumeric function will accept a single string value as an input argument. In the event that the value is null or empty we will return true as we can treat the value as zero. The routine will recognize a number that begins with a single, optional plus or minus sign followed by numbers, an optional decimal and more numbers.
((-|\+){0,1}[0-9]*.{0,1}[0-9]*)
If there are multiple matches on the regular expression then the value is not a number. A number can only match on this criteria once. If there are no matches at all then the value is not a number either.
So without further ado here is our simple IsNumeric routine!
using System.Text.RegularExpressions; private bool IsNumeric(string value) { if (string.IsNullOrEmpty(value)) return true; else { Regex testExpression = new Regex("((-|\\+){0,1}[0-9]*.{0,1}[0-9]*)"); MatchCollection matches = testExpression.Matches(value); if (!(matches == null) && (matches.Count == 1)) return true; } return false; }
Good function for a Utility library, did you consider accepting (####) as a numeric? This format is often used in accounting applications. Would be interested in hearing your opinion on accepting the (####) format. Also what about commas used in formatting?
Comment by Mike McCombs — March 25, 2011 @ 4:50 pm |
The following regular expression will work with currency and thousands separators. It will support the negative format as (100), ($100) or -100.
\({0,1}(\$|\+|-){0,1}([0-9]{1,3}(,[0-9]{3,3})*).[0-9]*\){0,1}
To use opening and closing parens to identify negative numbers without commas I modified the regular expression from the post.
\({0,1}(\$|\+|-){0,1}[0-9]*.[0-9]*\){0,1}
If you want to support both number formats then you have to test both conditions separately. Hope that helps!
Comment by Larry Steinle — March 28, 2011 @ 6:20 pm |