NaN 或 IsNumeric 的 C# 等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/437882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:23:11  来源:igfitidea点击:

What is the C# equivalent of NaN or IsNumeric?

c#parsing

提问by johnc

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.Parseor a regex (see below) but I was wondering if there is some built in way to do this, such as javascript's NaN()or IsNumeric()(was that VB, I can't remember?).

测试输入字符串是否包含数值(或相反不是数字)的最有效方法是什么?我想我可以使用Double.Parse正则表达式(见下文),但我想知道是否有一些内置的方法可以做到这一点,例如 javascriptNaN()IsNumeric()(那个 VB,我不记得了?)。

public static bool IsNumeric(this string value)
{
    return Regex.IsMatch(value, "^\d+$");
}

采纳答案by NotMe

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.

顺便说一下,所有标准数据类型,除了 GUID 的明显例外,都支持 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.

更新
secretwep 提出值“2345”将作为数字通过上述测试。但是,如果您需要确保字符串中的所有字符都是数字,则应采用另一种方法。

example 1:

示例 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)

更新 2(来自@stackonfire 处理空字符串或空字符串)

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

回答by shahkalpesh

VB has the IsNumericfunction. You could reference Microsoft.VisualBasic.dlland use it.

VB有这个IsNumeric功能。你可以参考Microsoft.VisualBasic.dll和使用它。

回答by Ed S.

Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.

是的,IsNumeric 是 VB。通常人们使用 TryParse() 方法,尽管它有点笨拙。正如你所建议的,你总是可以自己写。

int i;
if (int.TryParse(string, out i))
{

}

回答by Anthony Mastrean

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

我更喜欢这样的东西,它让你决定NumberStyle要测试什么。

public static Boolean IsNumeric(String input, NumberStyles numberStyle) {
    Double temp;
    Boolean result = Double.TryParse(input, numberStyle, CultureInfo.CurrentCulture, out temp);
    return result;
}

回答by Stu Mackellar

In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is notequivalent to a string that cannot be evaluated as a numeric value. NaN is usually understood as a numeric value used to represent the result of an "impossible" calculation - where the result is undefined. In this respect I would say the Javascript usage is slightly misleading. In C# NaN is defined as a property of the single and double numeric types and is used to refer explicitly to the result of diving zero by zero. Other languages use it to represent different "impossible" values.

除了前面的正确答案之外,可能值得指出的是,一般用法中的“非数字”(NaN)并不等同于无法计算为数值的字符串。NaN 通常被理解为一个数值,用于表示“不可能”计算的结果 - 结果未定义。在这方面,我会说 Javascript 的使用有点误导。在 C# 中,NaN 被定义为单双数值类型的属性,用于显式引用零除以零的结果。其他语言使用它来表示不同的“不可能”值。

回答by Mnaouar

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

回答by kenny

Maybe this is a C# 3 feature, but you could use double.NaN.

也许这是 C# 3 的功能,但您可以使用double.NaN.

回答by Madcat

Actually, Double.NaNis supported in all .NET versions 2.0 and greater.

实际上,Double.NaN所有 .NET 版本 2.0 及更高版本都支持。

回答by MrSiir

Simple extension:

简单扩展:

public static bool IsNumeric(this String str)
{
    try
    {
        Double.Parse(str.ToString());
        return true;
    }
    catch {
    }
    return false;
}

回答by secretwep

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:

我使用 Chris Lively 的片段(选定的答案)封装在一个 bool 函数中,如 Gishu 的建议一两年。在继续进一步处理之前,我用它来确保某些查询字符串只是数字。我开始收到一些标记答案未处理的错误查询字符串,特别是每当在“3645”之类的数字之后传递逗号时(返回 true)。这是由此产生的模式:

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