C# 中的 IsNumeric 函数

发布于 2025-01-16 19:43:06 字数 293 浏览 2 评论 0原文

我知道可以使用 try/catch 语句检查文本框或变量的值是否为数字,但 IsNumeric 简单得多。我当前的项目之一需要从文本框中恢复值。不幸的是,它是用 C# 编写的。

我知道有一种方法可以通过添加对 Visual Basic 的引用来在 Visual C# 中启用 Visual Basic IsNumeric 函数,但我不知道它的语法。我需要的是在 C# 中启用 IsNumeric 函数的清晰简洁的演练。我不打算使用任何其他 Visual Basic 固有的函数。

I know it's possible to check whether the value of a text box or variable is numeric using try/catch statements, but IsNumeric is so much simpler. One of my current projects requires recovering values from text boxes. Unfortunately, it is written in C#.

I understand that there's a way to enable the Visual Basic IsNumeric function in Visual C# by adding a reference to Visual Basic, though I don't know the syntax for it. What I need is a clear and concise walkthrough for enabling the IsNumeric function in C#. I don't plan on using any other functions indigenous to Visual Basic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

心安伴我暖 2025-01-23 19:43:06
public bool IsNumeric(string value)
{
    return value.All(char.IsNumber);
}
public bool IsNumeric(string value)
{
    return value.All(char.IsNumber);
}
情绪少女 2025-01-23 19:43:06

要完全窃取比尔的答案,您可以创建一个扩展方法并使用一些语法糖来帮助您。

创建一个类文件 StringExtensions.cs

内容:

public static class StringExt
{
    public static bool IsNumeric(this string text)
    {
        double test;
        return double.TryParse(text, out test);
    }
}

编辑:这是用于更新的 C# 7 语法。内联声明参数。

public static class StringExt
{
    public static bool IsNumeric(this string text) => double.TryParse(text, out _);
}

调用方法如下:

var text = "I am not a number";
text.IsNumeric()  //<--- returns false

To totally steal from Bill answer you can make an extension method and use some syntactic sugar to help you out.

Create a class file, StringExtensions.cs

Content:

public static class StringExt
{
    public static bool IsNumeric(this string text)
    {
        double test;
        return double.TryParse(text, out test);
    }
}

EDIT: This is for updated C# 7 syntax. Declaring out parameter in-line.

public static class StringExt
{
    public static bool IsNumeric(this string text) => double.TryParse(text, out _);
}

Call method like such:

var text = "I am not a number";
text.IsNumeric()  //<--- returns false
呆橘 2025-01-23 19:43:06

您可以创建一个辅助方法。像这样的东西:

public bool IsNumeric(string input) {
    int test;
    return int.TryParse(input, out test);
}

You could make a helper method. Something like:

public bool IsNumeric(string input) {
    int test;
    return int.TryParse(input, out test);
}
2025-01-23 19:43:06

值得一提的是,可以根据 Unicode 类别检查字符串中的字符 - 数字、大写字母、小写字母、货币等。以下是使用 Linq 检查字符串中数字的两个示例:

var containsNumbers = s.Any(Char.IsNumber);
var isNumber = s.All(Char.IsNumber);

为了清楚起见,上面的语法是以下语法的较短版本:

var containsNumbers = s.Any(c=>Char.IsNumber(c));
var isNumber = s.All(c=>Char.IsNumber(c));

链接到 MSDN 上的 unicode 类别:

UnicodeCategory 枚举

It is worth mentioning that one can check the characters in the string against Unicode categories - numbers, uppercase, lowercase, currencies and more. Here are two examples checking for numbers in a string using Linq:

var containsNumbers = s.Any(Char.IsNumber);
var isNumber = s.All(Char.IsNumber);

For clarity, the syntax above is a shorter version of:

var containsNumbers = s.Any(c=>Char.IsNumber(c));
var isNumber = s.All(c=>Char.IsNumber(c));

Link to unicode categories on MSDN:

UnicodeCategory Enumeration

自此以后,行同陌路 2025-01-23 19:43:06

使用 C# 7 (.NET Framework 4.6.2),您可以将 IsNumeric 函数编写为一行:

public bool IsNumeric(string val) => int.TryParse(val, out int result);

请注意,上面的函数仅适用于整数 (Int32)。但是您可以为其他数字数据类型实现相应的函数,例如 long、double 等。

Using C# 7 (.NET Framework 4.6.2) you can write an IsNumeric function as a one-liner:

public bool IsNumeric(string val) => int.TryParse(val, out int result);

Note that the function above will only work for integers (Int32). But you can implement corresponding functions for other numeric data types, like long, double, etc.

情绪操控生活 2025-01-23 19:43:06

http://msdn.microsoft.com/en-us/library/wkze6zky.aspx菜单


项目-->添加引用

单击:程序集、框架

在 Microsoft.VisualBasic 上打勾。

点击“确定”。

该链接适用于 Visual Studio 2013,您可以使用不同版本的 Visual Studio 的“其他版本”下拉列表。

在所有情况下,您都需要添加对 .NET 程序集“Microsoft.VisualBasic”的引用。

在 c# 文件的顶部,您需要:

using Microsoft.VisualBasic;

然后您可以查看编写代码。

代码类似于:

   private void btnOK_Click(object sender, EventArgs e)
   {
      if ( Information.IsNumeric(startingbudget) )
      {
         MessageBox.Show("This is a number.");
      }
   }

http://msdn.microsoft.com/en-us/library/wkze6zky.aspx

menu:
Project-->Add Reference

click: assemblies, framework

Put a checkmark on Microsoft.VisualBasic.

Hit OK.

That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.

In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".

At the top of your c# file you neeed:

using Microsoft.VisualBasic;

Then you can look at writing the code.

The code would be something like:

   private void btnOK_Click(object sender, EventArgs e)
   {
      if ( Information.IsNumeric(startingbudget) )
      {
         MessageBox.Show("This is a number.");
      }
   }
破晓 2025-01-23 19:43:06

尝试以下代码片段。

double myVal = 0;
String myVar = "Not Numeric Type";

if (Double.TryParse(myVar , out myNum)) {
  // it is a number
} else {
  // it is not a number
}

Try following code snippet.

double myVal = 0;
String myVar = "Not Numeric Type";

if (Double.TryParse(myVar , out myNum)) {
  // it is a number
} else {
  // it is not a number
}
空城缀染半城烟沙 2025-01-23 19:43:06

我通常使用扩展方法来处理这样的事情。以下是在控制台应用程序中实现的一种方法:

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckIfNumeric("A");
            CheckIfNumeric("22");
            CheckIfNumeric("Potato");
            CheckIfNumeric("Q");
            CheckIfNumeric("A&^*^");

            Console.ReadLine();
        }

        private static void CheckIfNumeric(string input)
        {
            if (input.IsNumeric())
            {
                Console.WriteLine(input + " is numeric.");
            }
            else
            {
                Console.WriteLine(input + " is NOT numeric.");
            }
        }
    }

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

输出:

A 不是数字。

22 是数字。

马铃薯不是数字。

Q 不是数字。

A&^*^ 不是数字。

注意,这里有一些使用正则表达式检查数字的其他方法。

I usually handle things like this with an extension method. Here is one way implemented in a console app:

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckIfNumeric("A");
            CheckIfNumeric("22");
            CheckIfNumeric("Potato");
            CheckIfNumeric("Q");
            CheckIfNumeric("A&^*^");

            Console.ReadLine();
        }

        private static void CheckIfNumeric(string input)
        {
            if (input.IsNumeric())
            {
                Console.WriteLine(input + " is numeric.");
            }
            else
            {
                Console.WriteLine(input + " is NOT numeric.");
            }
        }
    }

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

Output:

A is NOT numeric.

22 is numeric.

Potato is NOT numeric.

Q is NOT numeric.

A&^*^ is NOT numeric.

Note, here are a few other ways to check for numbers using RegEx.

空心空情空意 2025-01-23 19:43:06

使用 Net6 进行测试,并使用 object 进行测试,因为我的应用程序需要:

public static bool IsNumeric(this object text) => double.TryParse(Convert.ToString(text), out _);

可与 nullstring.empty 一起使用,并且还测试了 ""< /代码>。

Tested with Net6 and universal with object because needed in my app:

public static bool IsNumeric(this object text) => double.TryParse(Convert.ToString(text), out _);

Works with null and string.empty and also tested "".

灵芸 2025-01-23 19:43:06

我阅读了所有建议并进行了比较。
这个建议更好:

public static bool IsNumeric(string value) => double.TryParse(value, out _);

但是这个解决方案并不完美,因为不支持浮点数:

public bool static IsNumeric(string value)=>value.All(char.IsNumber);

i read all suggested and compare its.
this suggeste is better :

public static bool IsNumeric(string value) => double.TryParse(value, out _);

but this solusion is not perfect because is not support float number :

public bool static IsNumeric(string value)=>value.All(char.IsNumber);
红颜悴 2025-01-23 19:43:06
public static bool IsNumeric(string Value)
{
        return decimal.TryParse(Value, out _) || double.TryParse(Value, out _);
        /*
            decimal vs double:

            If a numeric value uses lot of decimal digits, it may not be convertible to 'double' type!
            If a numeric value is too big, it may not be convertible to 'decimal' type!

            Although in recent versions of Visual Studio Core, for number having too many decimal digits, 
            "double.TryParse(Value, out _)" returns "true" (which is not compatible with the conceptual 
            design of "double" type), it may not work in later versions of the compiler.

            Mr. "Jon Skeet" said some years ago:
            The range of a double value is much larger than the range of a decimal.
            0.1 is exactly representable in decimal but not in double, and decimal  
            actually uses a lot more bits for precision than double does.
        */
}
public static bool IsNumeric(string Value)
{
        return decimal.TryParse(Value, out _) || double.TryParse(Value, out _);
        /*
            decimal vs double:

            If a numeric value uses lot of decimal digits, it may not be convertible to 'double' type!
            If a numeric value is too big, it may not be convertible to 'decimal' type!

            Although in recent versions of Visual Studio Core, for number having too many decimal digits, 
            "double.TryParse(Value, out _)" returns "true" (which is not compatible with the conceptual 
            design of "double" type), it may not work in later versions of the compiler.

            Mr. "Jon Skeet" said some years ago:
            The range of a double value is much larger than the range of a decimal.
            0.1 is exactly representable in decimal but not in double, and decimal  
            actually uses a lot more bits for precision than double does.
        */
}
極樂鬼 2025-01-23 19:43:06
public bool isNumber(string text)
{
    text = text.Trim(' ', '\t', '\v', '\r', '\n');
    if (text == null || text == "")
        return false;
    else
    {
        int countSep = 0;
        foreach (char c in text) 
        {
            if (c <= '9' && c >= '0')
                continue;
            else if (c == '.' || c == ',')
            {
                countSep++;
                continue;
            }
            else
                return false;
        }
        if (countSep == 0 || countSep == 1) // if countSep == 0 the integer number, countSep == 1 the decimal number.
            return true;
        return false;
    }
}
public bool isNumber(string text)
{
    text = text.Trim(' ', '\t', '\v', '\r', '\n');
    if (text == null || text == "")
        return false;
    else
    {
        int countSep = 0;
        foreach (char c in text) 
        {
            if (c <= '9' && c >= '0')
                continue;
            else if (c == '.' || c == ',')
            {
                countSep++;
                continue;
            }
            else
                return false;
        }
        if (countSep == 0 || countSep == 1) // if countSep == 0 the integer number, countSep == 1 the decimal number.
            return true;
        return false;
    }
}
恍梦境° 2025-01-23 19:43:06

数字可以通过多种方式实现,但我用我的方式

public bool IsNumeric(string value)
{
    bool isNumeric = true;
    char[] digits = "0123456789".ToCharArray();
    char[] letters = value.ToCharArray();
    for (int k = 0; k < letters.Length; k++)
    {
        for (int i = 0; i < digits.Length; i++)
        {
            if (letters[k] != digits[i])
            {
                isNumeric = false;
                break;
            }
        }
    }
    return isNumeric;
}

Is numeric can be achieved via many ways, but i use my way

public bool IsNumeric(string value)
{
    bool isNumeric = true;
    char[] digits = "0123456789".ToCharArray();
    char[] letters = value.ToCharArray();
    for (int k = 0; k < letters.Length; k++)
    {
        for (int i = 0; i < digits.Length; i++)
        {
            if (letters[k] != digits[i])
            {
                isNumeric = false;
                break;
            }
        }
    }
    return isNumeric;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文