What is the C# equivalent of NaN or IsNumeric?

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

    I have a slightly different version which returns the number. I would guess that in most cases after testing the string you would want to use the number.

    public bool IsNumeric(string numericString, out Double numericValue)
    {
        if (Double.TryParse(numericString, out numericValue))
            return true;
        else
            return false;
    }
    
    0 讨论(0)
  • 2020-11-27 14:21

    In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is not equivalent 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.

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

    VB has the IsNumeric function. You could reference Microsoft.VisualBasic.dll and use it.

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

    Simple extension:

    public static bool IsNumeric(this String str)
    {
        try
        {
            Double.Parse(str.ToString());
            return true;
        }
        catch {
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-11-27 14:23

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

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

    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.

    int i;
    if (int.TryParse(string, out i))
    {
    
    }
    
    0 讨论(0)
提交回复
热议问题