如何检查字符串是否为数字?

mar*_*zzz 31 c#

我想知道C#如何检查一个字符串是否是一个数字(只是一个数字).

示例:

141241   Yes
232a23   No
12412a   No
Run Code Online (Sandbox Code Playgroud)

等等...

有特定的功能吗?

Jam*_*ack 61

查一查double.TryParse(),如果你在谈论相同的数字1,-23.14159.其他一些人建议int.TryParse(),但小数点会失败.

double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
    // It's a number!
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如Lukas在下面指出的那样,在使用小数分隔符解析数字时,我们应该注意线程文化,即这样做是安全的:

double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out num)


Bro*_*ass 57

如果您只想检查字符串是否都是数字(不在特定的数字范围内),您可以使用:

string test = "123";
bool allDigits = test.All(char.IsDigit);
Run Code Online (Sandbox Code Playgroud)

  • 惊人.我不明白为什么这不高. (3认同)
  • 需要注意的是,如果空字符串是不可接受的,则此解决方案将失败并显示""".所有(Char.IsDigit)`(它返回"true").你需要做`test.Any()&& test.All(Char.IsDigit)`. (3认同)
  • 使用System.Linq; (2认同)
  • 不适用于`float/double`值. (2认同)

Ash*_*nko 10

就在这里

int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Jam*_*ill 9

使用 Int32.TryParse()

int num;

bool isNum = Int32.TryParse("[string to test]", out num);

if (isNum)
{
    //Is a Number
}
else
{
    //Not a number
}
Run Code Online (Sandbox Code Playgroud)

MSDN参考


Jac*_*ope 6

用途int.TryParse():

string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);
Run Code Online (Sandbox Code Playgroud)

结果将是true如果它.


Jos*_*nig 6

是的 - 您可以在C#中使用Visual Basic .它是所有.NET; VB函数IsNumeric,IsDate等实际上是Information类的静态方法.所以这是你的代码:

using Microsoft.VisualBasic;
...
Information.IsNumeric( object );
Run Code Online (Sandbox Code Playgroud)

  • 老兄,我刚刚给了_C#_代码,用于在VisualBasic _namespace_中使用一些东西.阅读帖子和代码! (4认同)

Jal*_*aid 5

int value;
if (int.TryParse("your string", out value))
{
    Console.WriteLine(value);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我个人的最爱

private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}
Run Code Online (Sandbox Code Playgroud)