Identify if a string is a number
Asked Answered
F

27

943

If I have these strings:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

Is there a command, like IsNumeric() or something else, that can identify if a string is a valid number?

Forklift answered 21/5, 2009 at 18:6 Comment(8)
from their examples you can see they meant if the whole string represents a number.Calandracalandria
return str.All(Char.IsDigit);Bizerte
str.All(Char.IsDigit) will declare "3.14" false as well as "-2" and "3E14". Not to speak of: "0x10"Disconnect
It depends on what type of number you are trying to check. For integer numbers without separator (i.e. strings of decimal digits) this check works, and is the same of the accepted answer and the one implied in OP.Am‚lie
@AustinSalonen, I don't understand your point. #3 has letters (and only one number) so it should be false. If the user enters "ab2" then the assumption is that they don't understand and therefore we can't assume we understand what they intend.Kush
Oh my... I went briefly through the answers and I'm wondering if I should post one more answer with TryParse. What do you think? :D Ok, forget it.Jeanajeanbaptiste
@Calandracalandria thank you for your comment, you have NO idea how long I've been trying to parse a string double as an int and wondering why it was failing...Hamforrd
aaand my search for "one" "two" etc goes on...Spiers
B
1521
int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!

Bruell answered 21/5, 2009 at 18:8 Comment(11)
Though, I would use double.TryParse, since we want to know if it represents a number at all.Embowel
Function will return true if I pass string as "-123" or "+123". I Understand that integer has positive and negative values. But If this string is coming from user entered textbox then it should return false.Trinee
This is a good solution, until a user enters a value beyond -2,147,483,648 to 2,147,483,647, and then this silently failsPhrenic
try parsing 0,60 (that is a comma!) it is an invalid number but will be parsed as 60!Mouth
This is a little bit old answer but anyway, TryParse returns 0 if parsing won't succed so this method has flaws. I suggest checking by Regex or iterating chars.Mertiemerton
How about "NaN"?Staggs
I prefer to have extension method for this check: public static bool IsNumeric(this string text) { double _out; return double.TryParse(text, out _out); }Sulphide
Better to use "long.TryParse", for longest strings. for example "2082546844562" is a number but can't be parsed as integer.Tackle
@RDeveloper unlike JS, NaN isn't a number or even a concept in C#,Resolutive
There's a syntax error in the third example: it needs to be "out int _" not "out _".Nocti
what about 0123. It is a string, but not a 'numerical value'?Scarf
I
399

This will return true if input is all numbers. Don't know if it's any better than TryParse, but it will work.

Regex.IsMatch(input, @"^\d+$")

If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and $.

Regex.IsMatch(input, @"\d")

Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

Infix answered 21/5, 2009 at 19:8 Comment(13)
Building the regex once and for all would be much more efficient, though.Spray
@CFP +1...RegEx are always better than usual functions, when applicable!Crossgarnet
@MAXE: I would not agree. Regular expression checks are quite slow, so there are often better solutions if performance is under consideration.Lozengy
@MichalB. I'm with you on that! I would use a regex in this case because (1) it's a simple, readable way to solve the problem and (2) profiling hasn't identified it as a bottleneck in my (hypothetical) situation. Chances are BFree's answer (https://mcmap.net/q/53349/-identify-if-a-string-is-a-number) or the answer Lucas suggests in his comment would perform better.Infix
@Alek, regex may be the right solution, depending on the details of the problem. It's certainly not always better (@MAXE), but it's a good option in some cases, and this could be one of those cases.Infix
This solution is good if you don't really need checked number to be parsed. I used this to check if long string is valid identifier of some kind. I needed only a substring of this to later use, so it was useless for me to define big variable to hold parsed number that I never use. I forgot about Regex this time on my own, so thank you.Fawnia
When first character is 0, TryParse won't work. So In that case RegX will help.Rahal
you can add RegexOptions.Compiled as a parameter if you're running thousands of these for a possible speed increase Regex.IsMatch(x.BinNumber, @"\d", RegexOptions.Compiled)Southsoutheast
edit: you can add RegexOptions.Compiled as a parameter if you're running thousands of these for a possible speed increase Regex.IsMatch(x.BinNumber, @"^\d+$", RegexOptions.Compiled)Southsoutheast
will also fail on negatives and things with .Dibranchiate
@Noctis, true, but if you look at the original question (especially before the edits), the OP seemed to be looking for digits, not really for actual numbers. You're absolutely right that this simple regex would fail to parse many valid numbers.Infix
especially before the edits ...wow ... I'll admit I didn't dig THAT far ... :). Keep up the good work :)Dibranchiate
for any noobs out there you need to add: using System.Text.RegularExpressions; at the top of you visual studio classSketchbook
H
305

You can also use:

using System.Linq;

stringTest.All(char.IsDigit);

It will return true for all Numeric Digits (not float) and false if input string is any sort of alphanumeric.

Test case Return value Test result
"1234" true ✅Pass
"1" true ✅Pass
"0" true ✅Pass
"" true ⚠️Fail (known edge case)
"12.34" false ✅Pass
"+1234" false ✅Pass
"-13" false ✅Pass
"3E14" false ✅Pass
"0x10" false ✅Pass

Please note: stringTest should not be an empty string as this would pass the test of being numeric.

Homegrown answered 20/10, 2014 at 12:6 Comment(6)
That's very cool. One thing to be aware of though: an empty string will pass that test as being numeric.Zaremski
@Zaremski : I am glad, you like it. Yes, you are correct. I have updated note above. Thanks!Homegrown
this also does not work for decimal cases. The right test will be stringTest.All(l => char.IsDigit(l) || '.' == l || '-' == l);Behemoth
Thanks for your input Salman, To specifically check decimal out of a string, you can go for - if (Decimal.TryParse(stringTest2, out value)) { /* Yes, Decimal / } else { / No, Not a Decimal*/ }Homegrown
Salman, it's not that simple- this would pass ..--..-- as a valid number. Clearly not.Werby
Besides being more concise than the TryParse solutions, and supporting arbitrary length strings, this answer has the definite advantage of being more self-documenting -- if all you're looking for is just checking for digits (or empty) of course.Avalokitesvara
W
147

I've used this function several times:

public static bool IsNumeric(object Expression)
{
    double retNum;

    bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
    return isNum;
}

But you can also use;

bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false

From Benchmarking IsNumeric Options

alt text
(source: aspalliance.com)

alt text
(source: aspalliance.com)

Weiweibel answered 21/5, 2009 at 18:20 Comment(7)
referencing Microsoft.VisualBasic.dll from C# app? eww :PCalandracalandria
I have no problem to use "IsNumeric" it works good. Also you can see that there's little efficience difference between TryParse and IsNumeric. Remember that TryParse is new in 2.0 and before then it was better to use IsNumeric that any other strategy.Weiweibel
Well, VB.NET's IsNumeric() internally uses double.TryParse(), after a number of gyrations that are needed (among other things) for VB6 compatibility. If you don't need compatibility, double.TryParse() is just as simple to use, and it saves you from wasting memory by loading Microsoft.VisualBasic.dll in your process.Rountree
Quick note: using a regular expression will be much faster if you manage to have the underlying finite-state machine built once and for all. Generally, building the state machine takes O(2^n) where n is the length of the regex, whereas reading is O(k) where k is the length of the string being searched. So rebuilding the regex every time introduces a bias.Spray
Sorry but...there's nothing better of RegEx, in this case!Crossgarnet
@Calandracalandria Actually, there's some really nice stuff in there, like a full csv parser. No reason not to use it if it exists in there.Vinous
This answer, looks best to me , as this one if fastest considering above facts, and mentioned here also qawithexperts.com/questions/460/…Punt
R
34

This is probably the best option in C#.

If you want to know if the string contains a whole number (integer):

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can't, it returns false.

Solutions using the int.Parse(someString) alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(...) was added to the C# language in version 2, and until then you didn't have a choice. Now you do: you should therefore avoid the Parse() alternative.

If you want to accept decimal numbers, the decimal class also has a .TryParse(...) method. Replace int with decimal in the above discussion, and the same principles apply.

Rountree answered 21/5, 2009 at 18:16 Comment(1)
Why is TryParse better than comparing all the characters with integer characters?Vu
K
32

You can always use the built in TryParse methods for many datatypes to see if the string in question will pass.

Example.

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

Result would then = True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

Result would then = False

Kampong answered 21/5, 2009 at 18:9 Comment(1)
I think I may have done that more in VB style syntax than C#, but the same rules apply.Kampong
P
28

In case you don't want to use int.Parse or double.Parse, you can roll your own with something like this:

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}
Perimorph answered 21/5, 2009 at 18:13 Comment(5)
What if they meant integers only? What about locales where '.' is the group separator, not the comma (e.g. pt-Br)? what about negative numbers? group separators (commas in English)? currency symbols? TryParse() can manage all of these as required using NumberStyles and IFormatProvider.Calandracalandria
Ooh yeah, I like the All version better. I've never actually used that extension method, good call. Although it should be s.ToCharArray().All(..). As for your second point, I hear ya, which is why I prefaced with if you don't want to use int.Parse.... (which I'm assuming has more overhead...)Perimorph
1.3.3.8.5 is not really a number, though, while 1.23E5 is.Spray
@BFree: "Although it should be s.ToCharArray().All(..)" -- realizing I'm insanely late to the game, that's not true. Every string "is" already a char array. Neat, huh? Though the line is missing a char, or you'll get a Member 'char.IsDigit(char)' cannot be accessed with an instance reference; qualify it with a type name instead error: .All(c => char.IsDigit(c) || c == '.')) And @RusselYang - All logic is flawed; the question is which bugs you don't mind shipping. ;^) But I get your point.Notability
@Calandracalandria I agree that TryParse handles more, but sometimes that's not needed. I just need to validate my credit card number boxes (which can only have digits). This solution is almost definitely faster than try parse.Indulgent
W
15

If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:

// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)

// Finds whether the given variable is numeric.

// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.

// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
    new Regex(  "^(" +
                /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                /*Bin*/ @"0b[01]+"      + "|" + 
                /*Oct*/ @"0[0-7]*"      + "|" +
                /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                ")$" );
static bool IsNumeric( string value )
{
    return _isNumericRegex.IsMatch( value );
}

Unit Test:

static void IsNumericTest()
{
    string[] l_unitTests = new string[] { 
        "123",      /* TRUE */
        "abc",      /* FALSE */
        "12.3",     /* TRUE */
        "+12.3",    /* TRUE */
        "-12.3",    /* TRUE */
        "1.23e2",   /* TRUE */
        "-1e23",    /* TRUE */
        "1.2ef",    /* FALSE */
        "0x0",      /* TRUE */
        "0xfff",    /* TRUE */
        "0xf1f",    /* TRUE */
        "0xf1g",    /* FALSE */
        "0123",     /* TRUE */
        "0999",     /* FALSE (not octal) */
        "+0999",    /* TRUE (forced decimal) */
        "0b0101",   /* TRUE */
        "0b0102"    /* FALSE */
    };

    foreach ( string l_unitTest in l_unitTests )
        Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );

    Console.ReadKey( true );
}

Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).

Whortleberry answered 30/4, 2013 at 15:4 Comment(6)
Not trying to be a smart alec here, but this seems to fail for string "0". My Regex is non-existent. Is there a simple tweak for that? I get "0" and possibly "0.0" and even "-0.0" as possible valid numerics.Tempestuous
@SteveHibbert - Everyone knows that "0" isn't a number! Seriously though... adjusted the regex to match 0.Whortleberry
Hmmm, is it me, or is "0" still not recognised as numeric?Tempestuous
@SteveHibbert - Did you change the "oct" pattern to 0[0-7]* (with the star)? That should match a single 0. The "dec" pattern has been adjusted so that it will match one or more 0's if they are followed by a decimal point.Whortleberry
Being lazy, and regex-ignorant, I cut'n'pasted the code above, which looks like it includes the "0.0" type change. I ran a test to check that a string "0" running .IsNumeric(), and that returns false. I'm thinking that the Octal test will return true for anything that has two numeric chars where the first is zero (and the second is zero to seven), but will return false for just a big fat lonely zero on it's own. If you test "0", with the code above, do you get false? Apologies, if I knew more regex I'd be able to give better feedback. Must read up.Tempestuous
!Doh! Just re-read your comment above, I had missed the additional asterisk, I only updated the decimal line. With that in place, you're right, "0" IsNumeric. Apologies for the faffing about, and thanks very much for the update, hope it helps others out too. Much obliged.Tempestuous
C
15

I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

Simple to use:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

Or, if you want to test other types of number, you can specify the 'style'. So, to convert a number with an Exponent, you could use:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

Or to test a potential Hex string, you could use:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

The optional 'culture' parameter can be used in much the same way.

It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.

Cheyennecheyne answered 29/9, 2015 at 9:44 Comment(1)
Works great, except that Double.TryParse doesn't support NumberStyles.HexNumber. See MSDN Double.TryParse. Any reason why you TryParse before checking for IsNullOrWhiteSpace? TryParse returns false if IsNullOrWhiteSpace doesn't it?Disconnect
S
14

UPDATE of Kunal Noel Answer

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

But, for this case we have that empty strings will pass that test, so, you can:

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}
Schism answered 18/10, 2018 at 17:55 Comment(1)
This is the better answer as it does not actually convert the string to integer and run the risk of integer overflow.Delfeena
M
11

You can use TryParse to determine if the string can be parsed into an integer.

int i;
bool bNum = int.TryParse(str, out i);

The boolean will tell you if it worked or not.

Mongoloid answered 21/5, 2009 at 18:10 Comment(0)
E
11

If you want to know if a string is a number, you could always try parsing it:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

Note that TryParse returns a bool, which you can use to check if your parsing succeeded.

Estimation answered 21/5, 2009 at 18:11 Comment(0)
M
11

I guess this answer will just be lost in between all the other ones, but anyway, here goes.

I ended up on this question via Google because I wanted to check if a string was numeric so that I could just use double.Parse("123") instead of the TryParse() method.

Why? Because it's annoying to have to declare an out variable and check the result of TryParse() before you know if the parse failed or not. I want to use the ternary operator to check if the string is numerical and then just parse it in the first ternary expression or provide a default value in the second ternary expression.

Like this:

var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;

It's just a lot cleaner than:

var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
    //whatever you want to do with doubleValue
}

I made a couple extension methods for these cases:


Extension method one

public static bool IsParseableAs<TInput>(this string value) {
    var type = typeof(TInput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return false;

    var arguments = new[] { value, Activator.CreateInstance(type) };
    return (bool) tryParseMethod.Invoke(null, arguments);
}

Example:

"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;

Because IsParseableAs() tries to parse the string as the appropriate type instead of just checking if the string is "numeric" it should be pretty safe. And you can even use it for non numeric types that have a TryParse() method, like DateTime.

The method uses reflection and you end up calling the TryParse() method twice which, of course, isn't as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.

This method can also be used to easily parse a list of numeric strings into a list of double or some other type with a default value without having to catch any exceptions:

var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);

Extension method two

public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
    var type = typeof(TOutput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return defaultValue;

    var arguments = new object[] { value, null };
    return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}

This extension method lets you parse a string as any type that has a TryParse() method and it also lets you specify a default value to return if the conversion fails.

This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though...

Examples:

"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);

Outputs:

123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
Maddie answered 7/3, 2014 at 13:7 Comment(5)
I believe you may have invented one of the most inefficient approaches I've seen yet. Not only are you parsing the string twice (in the case that it's parseable), you are also calling reflection functions multiple times to do it. And, in the end, you don't even save any keystrokes using the extension method.Whortleberry
Thank you for just repeating what I wrote myself in the second to last paragraph. Also if you take my last example into account you definitely save keystrokes using this extension method. This answer doesn't claim to be some kind of a magic solution to any problem, it's merely a code example. Use it, or don't use it. I think it's convenient when used right. And it includes examples of both extension methods and reflection, maybe someone can learn from it.Pharyngeal
Have you tried var x = double.TryParse("2.2", new double()) ? double.Parse("2.2") : 0.0;?Whortleberry
Yes, and it doesn't work. Argument 2 must be passed with the 'out' keyword and if you specify out as well as new you get A ref or out argument must be an assignable variable.Pharyngeal
Performance TryParse is better than all exposed here. Results: TryParse 8 Regex 20 PHP IsNumeric 30 Reflections TryParse 31 Test code dotnetfiddle.net/x8GjAFToxicology
D
9

If you want to check if a string is a number (I'm assuming it's a string since if it's a number, duh, you know it's one).

  • Without regex and
  • using Microsoft's code as much as possible

you could also do:

public static bool IsNumber(this string aNumber)
{
     BigInteger temp_big_int;
     var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
     return is_number;
}

This will take care of the usual nasties:

  • Minus (-) or Plus (+) in the beginning
  • contains decimal character BigIntegers won't parse numbers with decimal points. (So: BigInteger.Parse("3.3") will throw an exception, and TryParse for the same will return false)
  • no funny non-digits
  • covers cases where the number is bigger than the usual use of Double.TryParse

You'll have to add a reference to System.Numerics and have using System.Numerics; on top of your class (well, the second is a bonus I guess :)

Dibranchiate answered 15/5, 2014 at 23:24 Comment(0)
Q
8

Double.TryParse

bool Double.TryParse(string s, out double result)
Quadrangular answered 21/5, 2009 at 18:11 Comment(0)
G
7

The best flexible solution with .net built-in function called- char.IsDigit. It works with unlimited long numbers. It will only return true if each character is a numeric number. I used it lot of times with no issues and much easily cleaner solution I ever found. I made a example method.Its ready to use. In addition I added validation for null and empty input. So the method is now totally bulletproof

public static bool IsNumeric(string strNumber)
    {
        if (string.IsNullOrEmpty(strNumber))
        {
            return false;
        }
        else
        {
            int numberOfChar = strNumber.Count();
            if (numberOfChar > 0)
            {
                bool r = strNumber.All(char.IsDigit);
                return r;
            }
            else
            {
                return false;
            }
        }
    }
Garbe answered 8/12, 2018 at 3:17 Comment(1)
str.All(Char.IsDigit) will declare "3.14" false as well as "-2" and "3E14". Not to speak of: "0x10" (as commented on an answer above by BlackTigerX)Justinajustine
S
6

Try the regex define below

new Regex(@"^\d{4}").IsMatch("6")    // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
Semitics answered 23/7, 2019 at 13:59 Comment(4)
Thanks that's the perfect solution for mePinkney
I needed to test the validity of a PIN, 4 digits and no 0 : new Regex(@"^[132465798]{4}").IsMatch(pin.Text)Pinkney
This should be the accepted answer. You shouldn't have to convert a string to a number to do this as if it's too long it will overflow.Cut
@EpicSpeedy my answer was too lateSemitics
D
2

With c# 7 it you can inline the out variable:

if(int.TryParse(str, out int v))
{
}
Dignitary answered 9/11, 2017 at 23:39 Comment(0)
I
2

Use these extension methods to clearly distinguish between a check if the string is numerical and if the string only contains 0-9 digits

public static class ExtensionMethods
{
    /// <summary>
    /// Returns true if string could represent a valid number, including decimals and local culture symbols
    /// </summary>
    public static bool IsNumeric(this string s)
    {
        decimal d;
        return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
    }

    /// <summary>
    /// Returns true only if string is wholy comprised of numerical digits
    /// </summary>
    public static bool IsNumbersOnly(this string s)
    {
        if (s == null || s == string.Empty)
            return false;

        foreach (char c in s)
        {
            if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
                return false;
        }

        return true;
    }
}
Ivette answered 3/7, 2018 at 9:59 Comment(0)
R
2
public static bool IsNumeric(this string input)
{
    int n;
    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
    {
        foreach (var i in input)
        {
            if (!int.TryParse(i.ToString(), out n))
            {
                return false;
            }

        }
        return true;
    }
    return false;
}
Reach answered 31/7, 2018 at 7:27 Comment(0)
P
2
Regex rx = new Regex(@"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
string text = "12.0";
var result = rx.IsMatch(text);
Console.WriteLine(result);

To check string is uint, ulong or contains only digits one .(dot) and digits Sample inputs

123 => True
123.1 => True
0.123 => True
.123 => True
0.2 => True
3452.434.43=> False
2342f43.34 => False
svasad.324 => False
3215.afa => False
Persistent answered 2/9, 2021 at 13:41 Comment(0)
U
1

Hope this helps

string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);

if isNumber 
{
//string is number
}
else
{
//string is not a number
}
Unlikelihood answered 2/1, 2013 at 11:32 Comment(0)
R
0

Pull in a reference to Visual Basic in your project and use its Information.IsNumeric method such as shown below and be able to capture floats as well as integers unlike the answer above which only catches ints.

    // Using Microsoft.VisualBasic;

    var txt = "ABCDEFG";

    if (Information.IsNumeric(txt))
        Console.WriteLine ("Numeric");

IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
Rimola answered 17/7, 2013 at 21:14 Comment(1)
A potential problem with this approach is that IsNumeric does a character analysis of the string. So a number like 9999999999999999999999999999999999999999999999999999999999.99999999999 will register as True, even though there is no way to represent this number using a standard numeric type.Whortleberry
Q
0

All the Answers are Useful. But while searching for a solution where the Numeric value is 12 digits or more (in my case), then while debugging, I found the following solution useful :

double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);

Th result variable will give you true or false.

Quackery answered 23/8, 2019 at 11:39 Comment(0)
S
0

I found the easiest one for the int comparison is

private bool IsNumeric(string text) { bool result = text.All(char.IsDigit); return isNum; }

Standing answered 29/11, 2023 at 11:38 Comment(0)
P
-1

Here is the C# method. Int.TryParse Method (String, Int32)

Passer answered 21/5, 2009 at 18:35 Comment(0)
G
-2

You can check each character of the string for its sequence number in the ASCII table. In the ASCII table , the characters '0','1',...'9' they stand in order and have positional numbers 48, 49,....57(decimal).

symbol ... '.' '/' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':' ';' '<' '=' ...
index ... 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 ...

Comparing the characters from the input string, we compare their indexes in the ASCII table and can find out whether it refers to a digit or not. If the whole string consists only of digits, then it is a number. Also added a check for the occurrence of a single separator character ('.').

 bool IsNumber(string str, char delimiter = '.')
    {
        if(str.Length==0) //Empty
        {
            return false;
        }
        bool isDelimetered = false;
        foreach (char c in str)
        {
            if ((c < '0' || c > '9') && (c != delimiter)) //ASCII table check. Not a digit && not delimeter
            {
                return false;
            }
            if (c == delimiter)
            {
                if (isDelimetered) //more than 1 delimiter
                {
                    return false;
                }
                else //first time delimiter
                {
                    isDelimetered = true;
                }
            }
        }
        return true; 
    }
Grath answered 3/2, 2023 at 13:43 Comment(3)
Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach? That's especially important here where there are over twenty existing answers, one with nearly 1,500 upvotes.Pensile
It works for the input in the question, but... it's extremely limited for the amount of coding one has to do and doesn't scale new features very well. E.g. Since you want to recognize decimal points, why not include e for exponentials or +/- signs? Also, this is C#, so please capitalize your method names and use camel/Pascal case in your identifiers instead of _.Bullyrag
There are many solutions offered here using TryParse. TryParse works great, but it's like magic, you get the result right away. I suggested an alternative, maybe someone will be interested in it.Grath

© 2022 - 2024 — McMap. All rights reserved.