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.

QUESTION:

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?

ANSWER:

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.

ANSWER:

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!

ANSWER:

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)

ANSWER:

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 caseReturn valueTest 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.