C#验证输入的是否数字:
public static bool IsNumber(string str)
{
for (int i = 0; i < str.Length; i++)
{
char[] a = str.ToCharArray();
if (48 > a[i] || a[i] > 57)
{
return false;
}
}
return true;
}
C#判断输入的是否为数字正则表达式的写法:
static bool IsNum(string str)
{
System.Text.RegularExpressions.Regex regNum
= new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
return regNum.IsMatch(str);
}
C#验证输入的是否为小数:
Decimal d;
string str= txtNum.Text.Trim();
try
{
d = Convert.ToDecimal(str);
}
catch
{
MessageBox.Show("输入不是有效的数字或小数! ");
}
if (str.StartsWith("0 ") && str.Length != 1 && str.IndexOf(". ") != 1 || str.IndexOf(". ") == 0)
{
MessageBox.Show("输入不是有效的数字或小数! ");
}
注: try...catch...效率要受一点小影响.