What is the C# equivalent of NaN or IsNumeric?

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

    I know this has been answered in many different ways, with extensions and lambda examples, but a combination of both for the simplest solution.

    public static bool IsNumeric(this String s)
    {
        return s.All(Char.IsDigit);
    }
    

    or if you are using Visual Studio 2015 (C# 6.0 or greater) then

    public static bool IsNumeric(this String s) => s.All(Char.IsDigit);
    

    Awesome C#6 on one line. Of course this is limited because it just tests for only numeric characters.

    To use, just have a string and call the method on it, such as:

    bool IsaNumber = "123456".IsNumeric();
    

提交回复
热议问题