What is the C# equivalent of NaN or IsNumeric?

后端 未结 15 1031
心在旅途
心在旅途 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

    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;
          }
       }
    

提交回复
热议问题