Identify if a string is a number – Dev

The best answers to the question “Identify if a string is a number” in the category Dev.


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?


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")

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


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!


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

alt text


You can also use:

using System.Linq;


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

Test caseReturn valueTest result
""true⚠️Fail (known edge case)

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