如何判断一字符串是否为有效数值,如
"0.123",".123","123,456,789.0","-.123","+0.123"等为有效数值。

解决方案 »

  1.   

    try
    {
      decimal a=Convert.ToDecimal("YourString");
      //correct
    }
    catch
    {
      //incorrect
    }
      

  2.   

    using System;
    using System.Text.RegularExpressions;public bool IsNumber(String strNumber)
    {
    Regex objNotNumberPattern=new Regex("[^0-9.-]");
    Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
    Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
    String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
    String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
    Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");return !objNotNumberPattern.IsMatch(strNumber) &&
    !objTwoDotPattern.IsMatch(strNumber) &&
    !objTwoMinusPattern.IsMatch(strNumber) &&
    objNumberPattern.IsMatch(strNumber);
    }
      

  3.   

    using System.Text.RegularExpressions;string strTemp = "0.123";
    Regex r = new Regex("((-?)|(+?))\d*.\d*");
    if (r.IsMatch(strTemp))
    {
        //符合
    }
      

  4.   

    lovefootball(蟑螂) 检测“-456,789.0”为无效
      

  5.   

    using System.Text.RegularExpressions;string strTemp = "0.123";
    Regex r = new Regex(@"^[+-]?\d*(,\d{3})*(\.\d+)?$");
    if (r.IsMatch(strTemp))
    {
        //符合
    }
      

  6.   

    lovefootball(蟑螂) 检测“.123”也无效
      

  7.   

    using System.Text.RegularExpressions;string strTemp = "0.123";
    Regex r = new Regex(@"^[+-]?\d*(,\d{3})*(\.\d+)?$");
    if (r.IsMatch(strTemp))
    {
        //符合
    }我的可以吗?