### 确定字符串是否为数字

1. `"abc"` = `false`

2. `"123"` = `true`

3. `"ab2"` = `false`

4. 是否有命令（如`IsNumeric()`或其他内容）可以识别字符串是否为有效数字？

#### 25 个答案:

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

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

var 可以替换为各自的类型！

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

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

``````stringTest.All(char.IsDigit);
``````

``````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
``````

（来源：aspalliance.com

（来源：aspalliance.com

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

TryParse方法将尝试将字符串转换为数字（整数），如果成功，它将返回true并将相应的数字放在myInt中。如果不能，则返回false。

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

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

``````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;
}
}
``````

``````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();
``````

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

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

``````// 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 (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
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 );
}
``````

``````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() );

}
``````

• 没有正则表达式和
• 尽可能使用Microsoft的代码

``````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不会解析带小数点的数字。 （所以：`BigInteger.Parse("3.3")`会抛出异常，`TryParse`同样会返回false）
• 没有搞笑的非数字
• 涵盖数量大于通常使用`Double.TryParse`
• 的情况

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

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

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

## 扩展方法一

``````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;
``````

``````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;
}
``````

<强>示例：

``````"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
``````

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

``````var numberString = "123";
int number;

int.TryParse(numberString , out number);
``````

Kunal Noel答案的更新

``````stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.
``````

``````if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
}
``````

``````public static class ExtensionMethods
{
/// <summary>
/// Returns true if string could represent a valid number, including decimals and local culture symbols
/// </summary>
public static bool IsNumeric(this string s)
{
decimal d;
return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
}

/// <summary>
/// Returns true only if string is wholy comprised of numerical digits
/// </summary>
public static bool IsNumbersOnly(this string s)
{
if (s == null || s == string.Empty)
return false;

foreach (char c in s)
{
if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
return false;
}

return true;
}
}
``````

``````if(int.TryParse(str, out int v))
{
}
``````

``````public static bool IsNumeric(this string input)
{
int n;
if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
{
foreach (var i in input)
{
if (!int.TryParse(i.ToString(), out n))
{
return false;
}

}
return true;
}
return false;
}
``````

``````string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);

if isNumber
{
//string is number
}
else
{
//string is not a number
}
``````

.net内置功能称为-`char.IsDigit`的最佳灵活解决方案。它可以使用无限长数字。仅当每个字符都是数字时才返回true。我使用它很多次，没有问题，而且找到的解决方案也更容易。我做了一个示例方法，可以使用了。另外，我添加了对空和空输入的验证。所以现在该方法是完全防弹的

``````public static bool IsNumeric(string strNumber)
{
if (string.IsNullOrEmpty(strNumber))
{
return false;
}
else
{
int numberOfChar = strNumber.Count();
if (numberOfChar > 0)
{
bool r = strNumber.All(char.IsDigit);
return r;
}
else
{
return false;
}
}
}
``````

``````    // Using Microsoft.VisualBasic;

var txt = "ABCDEFG";

if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");

IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
``````

``````double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
``````

``````import MessageKit
import UIKit

open class CustomCell: MessageContentCell {

open override func configure(with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) {
super.configure(with: message, at: indexPath, and: messagesCollectionView)

}

override open func layoutAccessoryView(with attributes: MessagesCollectionViewLayoutAttributes) {
// Accessory view is always on the opposite side of avatar
}

}
``````

``````//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");
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));
}

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;
}
``````