仅检查字符串中的数字和一个可选的小数点。

发布于 2024-08-18 04:32:38 字数 184 浏览 7 评论 0原文

我需要检查字符串是否只包含数字。我怎样才能在 C# 中实现这一目标?

string s = "123"    → valid 
string s = "123.67" → valid 
string s = "123F"   → invalid 

有没有像IsNumeric这样的函数?

I need to check if a string contains only digits. How could I achieve this in C#?

string s = "123"    → valid 
string s = "123.67" → valid 
string s = "123F"   → invalid 

Is there any function like IsNumeric?

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

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

发布评论

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

评论(9

水波映月 2024-08-25 04:32:38
double n;
if (Double.TryParse("128337.812738", out n)) {
  // ok
}

假设数字不会溢出

一个巨大字符串的双精度,请尝试正则表达式:

if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
  // ok
}

添加科学记数法(e/E)或+/-符号(如果需要)...

double n;
if (Double.TryParse("128337.812738", out n)) {
  // ok
}

works assuming the number doesn't overflow a double

for a huge string, try the regexp:

if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
  // ok
}

add in scientific notation (e/E) or +/- signs if needed...

梦巷 2024-08-25 04:32:38

摘自 MSDN(如何使用 Visual C# 实现 Visual Basic .NET IsNumeric 功能):

// IsNumeric Function
static bool IsNumeric(object Expression)
{
    // Variable to collect the Return value of the TryParse method.
    bool isNum;

    // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
    double retNum;

    // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
    // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
    isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
    return isNum;
}

Taken from MSDN (How to implement Visual Basic .NET IsNumeric functionality by using Visual C#):

// IsNumeric Function
static bool IsNumeric(object Expression)
{
    // Variable to collect the Return value of the TryParse method.
    bool isNum;

    // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
    double retNum;

    // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
    // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
    isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
    return isNum;
}
北方。的韩爷 2024-08-25 04:32:38

您可以使用 double.TryParse

string value;
double number;

if (Double.TryParse(value, out number))
   Console.WriteLine("valid");
else
   Console.WriteLine("invalid");

You can use double.TryParse

string value;
double number;

if (Double.TryParse(value, out number))
   Console.WriteLine("valid");
else
   Console.WriteLine("invalid");
傲鸠 2024-08-25 04:32:38

无论字符串有多长,这都应该有效:

string s = "12345";
bool iAllNumbers = s.ToCharArray ().All (ch => Char.IsDigit (ch) || ch == '.');

This should work no matter how long the string is:

string s = "12345";
bool iAllNumbers = s.ToCharArray ().All (ch => Char.IsDigit (ch) || ch == '.');
醉酒的小男人 2024-08-25 04:32:38

使用正则表达式是最简单的方法(但不是最快的方法):

bool isNumeric = Regex.IsMatch(s,@"^(\+|-)?\d+(\.\d+)?$");

Using regular expressions is the easiest way (but not the quickest):

bool isNumeric = Regex.IsMatch(s,@"^(\+|-)?\d+(\.\d+)?$");
弥枳 2024-08-25 04:32:38

如上所述,您可以使用 double.tryParse

如果您不喜欢那样(出于某种原因),您可以编写自己的扩展方法:

    public static class ExtensionMethods
    {
        public static bool isNumeric (this string str)
        {
            for (int i = 0; i < str.Length; i++ )
            {
                if ((str[i] == '.') || (str[i] == ',')) continue;    //Decide what is valid, decimal point or decimal coma
                if ((str[i] < '0') || (str[i] > '9')) return false;
            }

            return true;
        }
    }

用法:

string mystring = "123456abcd123";

if (mystring.isNumeric()) MessageBox.Show("The input string is a number.");
else MessageBox.Show("The input string is not a number.");

输入 :

123456abcd123

123.6

输出:

正确

As stated above you can use double.tryParse

If you don't like that (for some reason), you can write your own extension method:

    public static class ExtensionMethods
    {
        public static bool isNumeric (this string str)
        {
            for (int i = 0; i < str.Length; i++ )
            {
                if ((str[i] == '.') || (str[i] == ',')) continue;    //Decide what is valid, decimal point or decimal coma
                if ((str[i] < '0') || (str[i] > '9')) return false;
            }

            return true;
        }
    }

Usage:

string mystring = "123456abcd123";

if (mystring.isNumeric()) MessageBox.Show("The input string is a number.");
else MessageBox.Show("The input string is not a number.");

Input :

123456abcd123

123.6

Output:

false

true

川水往事 2024-08-25 04:32:38

我认为您可以在 Regex 类

Regex.IsMatch( yourStr, "\d" )

中使用正则表达式或类似的东西。

或者您可以使用 Parse 方法 int.Parse( ... )

I think you can use Regular Expressions, in the Regex class

Regex.IsMatch( yourStr, "\d" )

or something like that off the top of my head.

Or you could use the Parse method int.Parse( ... )

最美的太阳 2024-08-25 04:32:38

如果您接收字符串作为参数,更灵活的方法是使用正则表达式,如其他帖子中所述。
如果您获得用户的输入,您可以直接挂接 KeyDown 事件并忽略所有非数字键。这样你就可以确保你只有数字。

If you are receiving the string as a parameter the more flexible way would be to use regex as described in the other posts.
If you get the input from the user, you can just hook on the KeyDown event and ignore all keys that are not numbers. This way you'll be sure that you have only digits.

吃→可爱长大的 2024-08-25 04:32:38

这应该有效:

bool isNum = Integer.TryParse(Str, out Num);

This should work:

bool isNum = Integer.TryParse(Str, out Num);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文