C# 识别字符串是否为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/894263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 08:44:19  来源:igfitidea点击:

Identify if a string is a number

c#stringparsingisnumeric

提问by Gold

If I have these strings:

如果我有这些字符串:

  1. "abc"= false

  2. "123"= true

  3. "ab2"= false

  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?

是否有类似的命令IsNumeric()或其他命令可以识别字符串是否为有效数字?

采纳答案by mqp

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

UpdateAs of C# 7:

从 C# 7 开始更新

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

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

或者,如果您不需要该数字,则可以丢弃out 参数

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

The vars can be replaced by their respective types!

变种S可通过它们各自的类型来代替!

回答by TheTXI

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

对于许多数据类型,您始终可以使用内置的 TryParse 方法来查看相关字符串是否会通过。

Example.

例子。

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

Result would then = True

结果将 = True

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

Result would then = False

结果将 = False

回答by Craig

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

您可以使用 TryParse 来确定字符串是否可以解析为整数。

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

The boolean will tell you if it worked or not.

布尔值会告诉您它是否有效。

回答by Gabriel Florit

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 TryParsereturns a bool, which you can use to check if your parsing succeeded.

请注意,TryParse返回 a bool,您可以使用它来检查解析是否成功。

回答by Gabriel Florit

Double.TryParse

Double.TryParse

bool Double.TryParse(string s, out double result)

回答by BFree

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

如果你不想使用 int.Parse 或 double.Parse,你可以用这样的东西滚动你自己的:

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;
    }
}

回答by Euro Micelli

This is probably the best option in C#.

这可能是 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.

TryParse 方法将尝试将字符串转换为数字(整数),如果成功,它将返回 true 并将相应的数字放入 myInt。如果不能,则返回 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.

使用int.Parse(someString)其他响应中显示的替代方案的解决方案有效,但速度要慢得多,因为抛出异常非常昂贵。TryParse(...)在版本 2 中被添加到 C# 语言中,直到那时您别无选择。现在你这样做了:因此你应该避免Parse()选择。

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.

如果要接受十进制数,decimal 类也有.TryParse(...)方法。在上面的讨论中用十进制替换 int,同样的原则也适用。

回答by Nelson Miranda

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)

替代文字
(来源:aspalliance.com

alt text
(source: aspalliance.com)

替代文字
(来源:aspalliance.com

回答by Syed Tayyab Ali

回答by John M Gant

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

如果input是所有数字,这将返回 true 。不知道它是否比 更好TryParse,但它会起作用。

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.

编辑:实际上我认为它比 TryParse 更好,因为很长的字符串可能会溢出 TryParse。