如何识别string是否是数字?

如果我有这些string:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

是否有一个像IsNumeric或其他的命令,可以确定一个string是一个有效的数字?

 int n; bool isNumeric = int.TryParse("123", out n); 

更新从C#7开始:

 var isNumeric = int.TryParse("123", out var n); 

var s可以被它们各自的typesreplace!

如果input是全部数字,这将返回true。 不知道它是否比TryParse ,但它会工作。

 Regex.IsMatch(input, @"^\d+$") 

如果你只是想知道是否有一个或多个与字符混合的数字,请放弃^ +$

 Regex.IsMatch(input, @"\d") 

编辑:其实我认为它比TryParse更好,因为一个很长的string可能会溢出TryParse。

我已经多次使用这个函数了:

 public static bool IsNumeric(object Expression) { double retNum; bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); return isNum; } 

但是你也可以使用;

 bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false 

从标杆是数字选项

替代文字http://aspalliance.comhttp://img.dovov.comarticleimages/80/Figure1.gif

替代文字http://aspalliance.comhttp://img.dovov.comarticleimages/80/Figure2.gif

你也可以使用

  stringTest.All(char.IsDigit); 

它将返回所有数字数字(不是float )的真,如果inputstring是任何types的字母数字,则返回false

请注意 :stringtesting不应该是空string,因为这将通过testing是数字。

这可能是C#中的最佳select。

如果你想知道string是否包含整数(整数):

 string someString; // ... int myInt; bool isNumerical = int.TryParse(someString, out myInt); 

TryParse方法将尝试将string转换为数字(整数),如果成功,将返回true,并将相应的数字放在myInt中。 如果不能,则返回false。

使用其他响应中显示的int.Parse(someString)替代scheme的解决scheme起作用,但速度要慢得多,因为抛出exception非常昂贵。 TryParse(...)被添加到版本2中的C#语言,直到那时你没有select。 现在你这样做了:你应该避免使用Parse()方法。

如果要接受十进制数,则十进制类也有一个.TryParse(...)方法。 在上面的讨论中用intreplaceint,并且适用相同的原则。

对于许多数据types,您总是可以使用内置的TryParse方法来查看相关string是否会通过。

例。

 decimal myDec; var Result = decimal.TryParse("123", out myDec); 

结果会然后=真

 decimal myDec; var Result = decimal.TryParse("abc", out myDec); 

结果会然后=假

如果你不想使用int.Parse或double.Parse,你可以用这样的东西来滚动你自己:

 public static class Extensions { public static bool IsNumeric(this string s) { foreach (char c in s) { if (!char.IsDigit(c) && c != '.') { return false; } } return true; } } 

我知道这是一个古老的线程,但是没有一个答案真的对我有用 – 要么效率低下,要么不封装,以便于重用。 我也想确保它返回false如果string是空的或空的。 在这种情况下,TryParse返回true(一个空string在parsing为数字时不会导致错误)。 所以,这是我的string扩展方法:

 public static class Extensions { /// <summary> /// Returns true if string is numeric and not empty or null or whitespace. /// Determines if string is numeric by parsing as Double /// </summary> /// <param name="str"></param> /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param> /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param> /// <returns></returns> public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number, CultureInfo culture = null) { double num; if (culture == null) culture = CultureInfo.InvariantCulture; return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str); } } 

简单易用:

 var mystring = "1234.56789"; var test = mystring.IsNumeric(); 

或者,如果你想testing其他types的数字,你可以指定'样式'。 所以,要用Exponent转换一个数字,你可以使用:

 var mystring = "5.2453232E6"; var test = mystring.IsNumeric(style: NumberStyles.AllowExponent); 

或者testing一个潜在的hexstring,你可以使用:

 var mystring = "0xF67AB2"; var test = mystring.IsNumeric(style: NumberStyles.HexNumber) 

可选的“文化”参数可以以相同的方式使用。

由于不能转换太大而不能包含在double中的string,这是有限的,但这是一个有限的要求,我认为如果你使用的数字大于这个,那么你可能需要额外的专门的数字处理无论如何function。

如果你想要捕捉更广泛的数字,PHP的is_numeric ,你可以使用以下内容:

 // From PHP documentation for is_numeric // (http://php.net/manual/en/function.is-numeric.php) // Finds whether the given variable is numeric. // Numeric strings consist of optional sign, any number of digits, optional decimal part and optional // exponential part. Thus +0123.45e6 is a valid numeric value. // Hexadecimal (eg 0xf4c3b00c), Binary (eg 0b10100111001), Octal (eg 0777) notation is allowed too but // only without sign, decimal and exponential part. static readonly Regex _isNumericRegex = new Regex( "^(" + /*Hex*/ @"0x[0-9a-f]+" + "|" + /*Bin*/ @"0b[01]+" + "|" + /*Oct*/ @"0[0-7]*" + "|" + /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + ")$" ); static bool IsNumeric( string value ) { return _isNumericRegex.IsMatch( value ); } 

unit testing:

 static void IsNumericTest() { string[] l_unitTests = new string[] { "123", /* TRUE */ "abc", /* FALSE */ "12.3", /* TRUE */ "+12.3", /* TRUE */ "-12.3", /* TRUE */ "1.23e2", /* TRUE */ "-1e23", /* TRUE */ "1.2ef", /* FALSE */ "0x0", /* TRUE */ "0xfff", /* TRUE */ "0xf1f", /* TRUE */ "0xf1g", /* FALSE */ "0123", /* TRUE */ "0999", /* FALSE (not octal) */ "+0999", /* TRUE (forced decimal) */ "0b0101", /* TRUE */ "0b0102" /* FALSE */ }; foreach ( string l_unitTest in l_unitTests ) Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() ); Console.ReadKey( true ); } 

请记住,只是因为一个值是数字并不意味着它可以转换为数字types。 例如, "999999999999999999999999999999.9999999999"是完整的有效数字值,但不适合.NET数值types(不是在标准库中定义的数值types)。

如果你想检查一个string是否是一个数字(我假设它是一个string,因为如果它是一个数字,呃,你知道这是一个)。

  • 没有正则expression式和
  • 尽可能使用微软的代码

你也可以这样做:

 public static bool IsNumber(this string aNumber) { BigInteger temp_big_int; var is_number = BigInteger.TryParse(aNumber, out temp_big_int); return is_number; } 

这将照顾通常的坏事:

  • 减号( – )或加(+)在开始
  • 包含十进制字符 BigIntegers不会用小数点parsing数字。 (所以: BigInteger.Parse("3.3")将抛出一个exception,和TryParse相同将返回false)
  • 没有有趣的非数字
  • 涵盖的数字大于Double.TryParse通常使用的情况

您将不得不添加对System.Numerics的引用并using System.Numerics; 在你的class级之上(好吧,第二个是我想要的奖金:)

您可以使用TryParse来确定该string是否可以被parsing为一个整数。

 int i; bool bNum = int.TryParse(str, out i); 

布尔值会告诉你它是否工作。

我想这个答案只会在所有其他的答案之间丢失,但无论如何,在这里。

我通过Google结束了这个问题,因为我想检查一个stringnumeric以便我可以使用double.Parse("123")而不是TryParse()方法。

为什么? 因为如果parsing失败或者没有声明outvariables并且在你之前检查TryParse()的结果是烦人的。 我想使用ternary operator来检查string是否是numerical ,然后在第一个三元expression式中parsing它,或者在第二个三元expression式中提供默认值。

喜欢这个:

 var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0; 

这比以下更清洁:

 var doubleValue = 0; if (double.TryParse(numberAsString, out doubleValue)) { //whatever you want to do with doubleValue } 

我为这些情况做了一些extension methods


扩展方法一

 public static bool IsParseableAs<TInput>(this string value) { var type = typeof(TInput); var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, new[] { typeof(string), type.MakeByRefType() }, null); if (tryParseMethod == null) return false; var arguments = new[] { value, Activator.CreateInstance(type) }; return (bool) tryParseMethod.Invoke(null, arguments); } 

例:

 "123".IsParseableAs<double>() ? double.Parse(sNumber) : 0; 

因为IsParseableAs()尝试将stringparsing为适当的types,而不是仅仅检查string是否是“数字”,它应该是非常安全的。 甚至可以将它用于具有TryParse()方法的非数字types,如DateTime

该方法使用reflection,最后调用TryParse()方法两次,这当然不是那么高效,但并不是所有的东西都要被完全优化,有时方便性更重要。

这个方法也可以用来轻松地将一个数字string列表parsing成一个doubletypes的列表或者其他一些具有默认值的types,而不必捕获任何exception:

 var sNumbers = new[] {"10", "20", "30"}; var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0); 

扩展方法二

 public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) { var type = typeof(TOutput); var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, new[] { typeof(string), type.MakeByRefType() }, null); if (tryParseMethod == null) return defaultValue; var arguments = new object[] { value, null }; return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue; } 

这种扩展方法可以让你将一个stringparsing为任何具有TryParse()方法的type ,并且还可以让你指定一个默认值,以便在转换失败时返回。

这比使用上述扩展方法的三元运算符更好,因为它只转换一次,仍然使用reflection…

例子:

 "123".ParseAs<int>(10); "abc".ParseAs<int>(25); "123,78".ParseAs<double>(10); "abc".ParseAs<double>(107.4); "2014-10-28".ParseAs<DateTime>(DateTime.MinValue); "monday".ParseAs<DateTime>(DateTime.MinValue); 

输出:

 123 25 123,78 107,4 28.10.2014 00:00:00 01.01.0001 00:00:00 

Double.TryParse

 bool Double.TryParse(string s, out double result) 

如果你想知道一个string是否是一个数字,你总是可以尝试parsing它:

 var numberString = "123"; int number; int.TryParse(numberString , out number); 

请注意, TryParse返回一个bool ,您可以使用它来检查parsing是否成功。

希望这可以帮助

 string myString = "abc"; double num; bool isNumber = double.TryParse(myString , out num); if isNumber { //string is number } else { //string is not a number } 

这里是C#方法。 Int.TryParse方法(string,Int32)

在项目中引用Visual Basic并使用其Information.IsNumeric方法(如下所示),并且能够捕获浮点数以及整数,而不像上面只捕获整数的答案。

  // Using Microsoft.VisualBasic; var txt = "ABCDEFG"; if (Information.IsNumeric(txt)) Console.WriteLine ("Numeric"); IsNumeric("12.3"); // true IsNumeric("1"); // true IsNumeric("abc"); // false 

用c#7,你可以内联outvariables:

 if(int.TryParse(str, out int v)) { } 
 //To my knowledge I did this in a simple way static void Main(string[] args) { string a, b; int f1, f2, x, y; Console.WriteLine("Enter two inputs"); a = Convert.ToString(Console.ReadLine()); b = Console.ReadLine(); f1 = find(a); f2 = find(b); if (f1 == 0 && f2 == 0) { x = Convert.ToInt32(a); y = Convert.ToInt32(b); Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString()); } else Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b)); Console.ReadKey(); } static int find(string s) { string s1 = ""; int f; for (int i = 0; i < s.Length; i++) for (int j = 0; j <= 9; j++) { string c = j.ToString(); if (c[0] == s[i]) { s1 += c[0]; } } if (s == s1) f = 0; else f = 1; return f; }