一、利用Char.IsNumber()
/// <summary>
/// 判断字符串是否是纯数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
privatebool IsAllNum(string str)
{
if (str == null || str.Length == 0)
{
return false;
}
foreach (char c in str)
{
if (!Char.IsNumber(c))
{
return false;
}
}
return true;
}
二、利用正则 using System.Text.RegularExpressions;
/// <summary>
/// 验证字符串是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private bool IsNum(string str)
{
Regex r = new Regex(@"^[+-]?\d*(,\d{3})*(\.\d+)?$");
if (r.IsMatch(str))
{
return true;
}
return false;
}
三、利用异常
/// <summary>
/// 验证字符串是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private bool IsNumber(string str)
{
try
{
double.Parse(str);
return true;
}
catch {
return false;
}
}