What is the C# equivalent of NaN or IsNumeric?

后端 未结 15 938
心在旅途
心在旅途 2020-11-27 14:06

What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use Double.Parse or a

相关标签:
15条回答
  • 2020-11-27 14:08

    I like the extension method, but don't like throwing exceptions if possible. I opted for an extension method taking the best of 2 answers here.

        /// <summary>
        /// Extension method that works out if a string is numeric or not
        /// </summary>
        /// <param name="str">string that may be a number</param>
        /// <returns>true if numeric, false if not</returns>
        public static bool IsNumeric(this String str)
        {
            double myNum = 0;
            if (Double.TryParse(str, out myNum))
            {
                return true;
            }
            return false;
        }
    
    0 讨论(0)
  • 2020-11-27 14:10

    You can still use the Visual Basic function in C#. The only thing you have to do is just follow my instructions shown below:

    1. Add the reference to the Visual Basic Library by right clicking on your project and selecting "Add Reference":

    enter image description here

    1. Then import it in your class as shown below:

      using Microsoft.VisualBasic;

    2. Next use it wherever you want as shown below:

                  if (!Information.IsNumeric(softwareVersion))
              {
                  throw new DataException(string.Format("[{0}] is an invalid App Version!  Only numeric values are supported at this time.", softwareVersion));
              }
      

    Hope, this helps and good luck!

    0 讨论(0)
  • 2020-11-27 14:11

    I prefer something like this, it lets you decide what NumberStyle to test for.

    public static Boolean IsNumeric(String input, NumberStyles numberStyle) {
        Double temp;
        Boolean result = Double.TryParse(input, numberStyle, CultureInfo.CurrentCulture, out temp);
        return result;
    }
    
    0 讨论(0)
  • 2020-11-27 14:13

    This doesn't have the regex overhead

    double myNum = 0;
    String testVar = "Not A Number";
    
    if (Double.TryParse(testVar, out myNum)) {
      // it is a number
    } else {
      // it is not a number
    }
    

    Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.

    update
    secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.

    example 1:

    public Boolean IsNumber(String s) {
      Boolean value = true;
      foreach(Char c in s.ToCharArray()) {
        value = value && Char.IsDigit(c);
      }
    
      return value;
    }
    

    or if you want to be a little more fancy

    public Boolean IsNumber(String value) {
      return value.All(Char.IsDigit);
    }
    

    update 2 ( from @stackonfire to deal with null or empty strings)

    public Boolean IsNumber(String s) { 
        Boolean value = true; 
        if (s == String.Empty || s == null) { 
            value=false; 
        } else { 
            foreach(Char c in s.ToCharArray()) { 
                value = value && Char.IsDigit(c); 
            } 
        } return value; 
    }
    
    0 讨论(0)
  • 2020-11-27 14:13
    public static bool IsNumeric(string anyString)
    {
        if (anyString == null)
        {
            anyString = "";
        }
    
        if (anyString.Length > 0)
        {
            double dummyOut = new double();
            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);
            return Double.TryParse(anyString, System.Globalization.NumberStyles.Any, cultureInfo.NumberFormat, out dummyOut);
        }
        else
        {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:13

    I was using Chris Lively's snippet (selected answer) encapsulated in a bool function like Gishu's suggestion for a year or two. I used it to make sure certain query strings were only numeric before proceeding with further processing. I started getting some errant querystrings that the marked answer was not handling, specifically, whenever a comma was passed after a number like "3645," (returned true). This is the resulting mod:

       static public bool IsNumeric(string s)
       {
          double myNum = 0;
          if (Double.TryParse(s, out myNum))
          {
             if (s.Contains(",")) return false;
             return true;
          }
          else
          {
             return false;
          }
       }
    
    0 讨论(0)
提交回复
热议问题