How do I identify if a string is a number?

2018-12-31 03:33发布

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?

23条回答
不再属于我。
2楼-- · 2018-12-31 04:03

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.

查看更多
美炸的是我
3楼-- · 2018-12-31 04:04

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 http://aspalliance.com/images/articleimages/80/Figure1.gif

alt text http://aspalliance.com/images/articleimages/80/Figure2.gif

查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 04:04

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楼-- · 2018-12-31 04:07

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
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 04:09

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

查看更多
倾城一夜雪
7楼-- · 2018-12-31 04:11

You can also use:

stringTest.All(char.IsDigit);

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

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

查看更多
登录 后发表回答