What is the C# equivalent of NaN or IsNumeric?

后端 未结 15 1000
心在旅途
心在旅途 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: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; 
    }
    

提交回复
热议问题