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?

8
  • 82
    from their examples you can see they meant if the whole string represents a number.
    – Lucas
    May 21, 2009 at 18:32
  • 58
    return str.All(Char.IsDigit);
    – Mohsen
    Oct 23, 2013 at 5:45
  • 18
    str.All(Char.IsDigit) will declare "3.14" false as well as "-2" and "3E14". Not to speak of: "0x10" Oct 20, 2014 at 11:52
  • 4
    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. Aug 22, 2015 at 10:01
  • 1
    @Lucas 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...
    – Novastorm
    Mar 22, 2018 at 14:52

27 Answers 27

1522
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!

11
  • 166
    Though, I would use double.TryParse, since we want to know if it represents a number at all. May 21, 2009 at 18:31
  • 7
    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. Aug 28, 2013 at 13:58
  • 18
    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 fails Oct 23, 2014 at 22:05
  • 6
    I prefer to have extension method for this check: public static bool IsNumeric(this string text) { double _out; return double.TryParse(text, out _out); }
    – Baloo0ch
    Jan 21, 2018 at 19:05
  • 4
    Better to use "long.TryParse", for longest strings. for example "2082546844562" is a number but can't be parsed as integer. Mar 13, 2018 at 12:47
398

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.

13
  • 2
    Building the regex once and for all would be much more efficient, though.
    – Clément
    Jan 5, 2011 at 17:30
  • 24
    @MAXE: I would not agree. Regular expression checks are quite slow, so there are often better solutions if performance is under consideration.
    – Michal B.
    Dec 18, 2012 at 12:49
  • 8
    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) Nov 22, 2013 at 22:39
  • 14
    will also fail on negatives and things with .
    – Noctis
    May 15, 2014 at 23:13
  • 5
    for any noobs out there you need to add: using System.Text.RegularExpressions; at the top of you visual studio class
    – BenKoshy
    Nov 3, 2015 at 0:26
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.

6
  • 34
    That's very cool. One thing to be aware of though: an empty string will pass that test as being numeric.
    – dan-gph
    Jun 5, 2015 at 6:04
  • 2
    @dan-gph : I am glad, you like it. Yes, you are correct. I have updated note above. Thanks!
    – Kunal Goel
    Jun 6, 2015 at 7:15
  • 3
    this also does not work for decimal cases. The right test will be stringTest.All(l => char.IsDigit(l) || '.' == l || '-' == l); Feb 24, 2016 at 14:28
  • 1
    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*/ }
    – Kunal Goel
    Feb 26, 2016 at 5:38
  • 9
    Salman, it's not that simple- this would pass ..--..-- as a valid number. Clearly not.
    – Flynn1179
    Apr 11, 2016 at 12:26
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)

7
  • 91
    referencing Microsoft.VisualBasic.dll from C# app? eww :P
    – Lucas
    May 21, 2009 at 18:44
  • 12
    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. May 21, 2009 at 20:06
  • 4
    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.
    – Clément
    Jan 5, 2011 at 17:29
  • 2
    @Lucas 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.
    – Nyerguds
    Apr 4, 2016 at 12:04
  • 1
    This answer, looks best to me , as this one if fastest considering above facts, and mentioned here also qawithexperts.com/questions/460/…
    – user13993546
    Jun 21, 2022 at 6:50
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.

1
  • Why is TryParse better than comparing all the characters with integer characters?
    – jimjim
    Nov 7, 2019 at 6:09
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

1
  • I think I may have done that more in VB style syntax than C#, but the same rules apply.
    – TheTXI
    May 21, 2009 at 18:10
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;
    }
}
5
  • 7
    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.
    – Lucas
    May 21, 2009 at 18:43
  • 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...)
    – BFree
    May 21, 2009 at 19:03
  • 11
    1.3.3.8.5 is not really a number, though, while 1.23E5 is.
    – Clément
    Jan 5, 2011 at 17:31
  • @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.
    – ruffin
    Aug 15, 2014 at 20:19
  • 2
    @Lucas 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. Sep 12, 2014 at 16:41
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).

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. Mar 25, 2014 at 10:41
  • @SteveHibbert - Everyone knows that "0" isn't a number! Seriously though... adjusted the regex to match 0.
    – JDB
    Mar 25, 2014 at 13:30
  • Hmmm, is it me, or is "0" still not recognised as numeric? Mar 25, 2014 at 15:35
  • 1
    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. Mar 26, 2014 at 9:21
  • 1
    !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. Mar 26, 2014 at 13:58
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.

1
  • 2
    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? Nov 16, 2015 at 8:02
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
}
1
  • 3
    This is the better answer as it does not actually convert the string to integer and run the risk of integer overflow. Nov 25, 2020 at 6:55
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.

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.

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
5
  • 4
    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.
    – JDB
    Mar 25, 2014 at 16:53
  • 2
    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. Mar 25, 2014 at 21:40
  • 5
    Have you tried var x = double.TryParse("2.2", new double()) ? double.Parse("2.2") : 0.0;?
    – JDB
    Mar 26, 2014 at 14:42
  • 2
    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. Oct 22, 2015 at 7:50
  • 1
    Performance TryParse is better than all exposed here. Results: TryParse 8 Regex 20 PHP IsNumeric 30 Reflections TryParse 31 Test code dotnetfiddle.net/x8GjAF
    – elpezganzo
    Aug 25, 2017 at 7:42
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 :)

8

Double.TryParse

bool Double.TryParse(string s, out double result)
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;
            }
        }
    }
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)
    – Umar T.
    Jul 22, 2022 at 12:30
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)
4
  • 1
    Thanks that's the perfect solution for me
    – geriwald
    Feb 2, 2021 at 10:44
  • I needed to test the validity of a PIN, 4 digits and no 0 : new Regex(@"^[132465798]{4}").IsMatch(pin.Text)
    – geriwald
    Feb 2, 2021 at 10:50
  • 1
    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. Mar 28, 2021 at 21:27
  • @EpicSpeedy my answer was too late Mar 30, 2021 at 14:48
2

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

if(int.TryParse(str, out int v))
{
}
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;
    }
}
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;
}
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
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
}
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
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.
    – JDB
    Mar 25, 2014 at 16:35
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.

0

I found the easiest one for the int comparison is

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

-1

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

0
-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; 
    }
3
  • 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. Feb 9, 2023 at 0:50
  • 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 _. Feb 9, 2023 at 13:58
  • 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.
    – M.Max
    May 31, 2023 at 11:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.