What is the C# equivalent of NaN or IsNumeric?

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

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

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-27 14:33

    This is a modified version of the solution proposed by Mr Siir. I find that adding an extension method is the best solution for reuse and simplicity in the calling method.

    public static bool IsNumeric(this String s)
    {
        try { double.Parse(s); return true; }
        catch (Exception) { return false; }
    }
    

    I modified the method body to fit on 2 lines and removed the unnecessary .ToString() implementation. For those not familiar with extension methods here is how to implement:

    Create a class file called ExtensionMethods. Paste in this code:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace YourNameSpaceHere
    {
        public static class ExtensionMethods
        {
            public static bool IsNumeric(this String s)
            {
                try { double.Parse(s); return true; }
                catch (Exception) { return false; }
            }
        }
    }
    

    Replace YourNameSpaceHere with your actual NameSpace. Save changes. Now you can use the extension method anywhere in your app:

    bool validInput = stringVariable.IsNumeric();
    

    Note: this method will return true for integers and decimals, but will return false if the string contains a comma. If you want to accept input with commas or symbols like "$" I would suggest implementing a method to remove those characters first then test if IsNumeric.

    0 讨论(0)
提交回复
热议问题