我正在使用Visual Studio 2010。我想检查一个字符串是否为数字。有没有内置的函数可以检查这个,还是我们需要编写自定义代码?
string s = ...
int result;
if (int.TryParse(s, out result))
{
// The string was a valid integer => use result here
}
else
{
// invalid integer
}
除了整型以外,还有针对其他数字类型的 float.TryParse, double.TryParse 和 decimal.TryParse 方法可用。
string s = "sdf34";
Int32 a;
if (Int32.TryParse(s, out a))
{
// Value is numberic
}
else
{
//Not a valid number
}
int.TryParse(...)
,检查out bool
参数即可。public static bool IsNumber(String str)
{
try
{
Double.Parse(str);
return true;
}
catch (Exception)
{
return false;
}
}
所有的Double/Int32/... TryParse(...)
方法的问题在于,当数字字符串足够长时,该方法将返回false;
例如:
var isValidNumber = int.TryParse("9999999999", out result);
这里,isValidNumber
是 false 而 result
是 0,尽管给定的字符串是数值型的。
如果您不需要将字符串作为 int 使用,我建议在此使用正则表达式验证:
var isValidNumber = Regex.IsMatch(input, @"^\d+$")
这将仅匹配整数。例如,“123.45”将失败。
如果您需要检查浮点数:
var isValidNumber = Regex.IsMatch(input, @"^[0-9]+(\.[0-9]+)?$")
试试这个:
string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
MessageBox.Show(Num.ToString());
else
`enter code here`MessageBox.Show("Invalid number");
using System;
namespace ConsoleApplication1
{
class Test
{
public static void Main(String[] args)
{
bool check;
string testStr = "ABC";
string testNum = "123";
check = CheckNumeric(testStr);
Console.WriteLine(check);
check = CheckNumeric(testNum);
Console.WriteLine(check);
Console.ReadKey();
}
public static bool CheckNumeric(string input)
{
int outPut;
if (int.TryParse(input, out outPut))
return true;
else
return false;
}
}
}
这对你来说会起作用的!!
string val=...;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric(val);
TryParse
的人是正确的,但请记住,默认情况下会使用服务器上活动的当前文化进行解析。如果您期望特定的文化,则需要显式传递它。 - Lucero