string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
-6
对于许多数据类型,您始终可以使用内置的TryParse方法来查看相关字符串是否会通过 .
例 .
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
然后结果= True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
结果将= False
5
使用c#7,您可以内联out变量:
if(int.TryParse(str, out int v))
{
}
31
使用这些扩展方法可以清楚地区分检查字符串是否为数字以及字符串是否仅包含0-9位数
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;
}
}
1
如果您想知道字符串是否为数字,您可以尝试解析它:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
请注意 TryParse 返回 bool ,您可以使用它来检查解析是否成功 .
2
这可能是C#中最好的选择 .
如果您想知道字符串是否包含整数(整数):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
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;
}
}
stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.
但是,对于这种情况,我们有空字符串将通过该测试,因此,您可以:
if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
// Do your logic here
}
11
//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;
}
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();
// 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.
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 );
}
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;
}
23 回答
希望这可以帮助
对于许多数据类型,您始终可以使用内置的TryParse方法来查看相关字符串是否会通过 .
例 .
然后结果= True
结果将= False
使用c#7,您可以内联out变量:
使用这些扩展方法可以清楚地区分检查字符串是否为数字以及字符串是否仅包含0-9位数
如果您想知道字符串是否为数字,您可以尝试解析它:
请注意
TryParse
返回bool
,您可以使用它来检查解析是否成功 .这可能是C#中最好的选择 .
如果您想知道字符串是否包含整数(整数):
TryParse方法将尝试将字符串转换为数字(整数),如果成功,它将返回true并将相应的数字放在myInt中 . 如果不能,则返回false .
使用其他响应中显示的
int.Parse(someString)
替代方案的解决方案可行,但速度要慢得多,因为抛出异常非常昂贵 .TryParse(...)
已添加到版本2中的C#语言,在此之前您没有选择 . 现在你做了:因此你应该避免使用Parse()
替代方案 .如果要接受十进制数,则十进制类也具有
.TryParse(...)
方法 . 在上面的讨论中用int替换int,并且适用相同的原则 .您还可以使用:
如果输入字符串是任何类型的字母数字,它将为所有数字数字(不是
float
)和false
返回true
.Please note :
stringTest
不应该是空字符串,因为这会通过数字测试 .如果您不想使用int.Parse或double.Parse,您可以使用以下内容滚动自己:
在项目中引入对Visual Basic的引用,并使用其Information.IsNumeric方法,如下所示,并且能够捕获浮点数和整数,这与上面仅捕获整数的答案不同 .
Double.TryParse
UPDATE of Kunal Noel Answer
但是,对于这种情况,我们有空字符串将通过该测试,因此,您可以:
我想这个答案只会在所有其他答案之间丢失,但无论如何,这里也是如此 .
我最终通过谷歌来回答这个问题,因为我想检查
string
是否为numeric
,以便我可以使用double.Parse("123")
而不是TryParse()
方法 .为什么?因为如果解析失败,必须声明一个
out
变量并检查TryParse()
的结果是很烦人的 . 我想使用ternary operator
检查string
是否numerical
然后只是在第一个三元表达式中解析它或在第二个三元表达式中提供默认值 .像这样:
它比以下更清洁:
I made a couple extension methods for these cases:
扩展方法一
Example:
因为
IsParseableAs()
尝试将字符串解析为适当的类型而不是仅仅检查字符串是否为"numeric"它应该是非常安全的 . 您甚至可以将它用于具有TryParse()
方法的非数字类型,例如DateTime
.该方法使用反射,你最终调用
TryParse()
方法两次,当然效率不高,但不是所有东西都必须完全优化,有时方便更重要 .此方法还可用于轻松地将数字字符串列表解析为
double
列表或具有默认值的其他类型,而不必捕获任何异常:扩展方法二
此扩展方法允许您将
string
解析为具有TryParse()
方法的任何type
,并且还允许您指定在转换失败时返回的默认值 .这比使用三元运算符和上面的扩展方法更好,因为它只进行一次转换,但仍使用反射...
Examples:
Outputs:
具有.net内置功能的最佳灵活解决方案称为
char.IsDigit
. 它适用于无限长号码 . 如果每个字符都是数字,它只会返回true . 我曾多次使用它,没有任何问题,而且我发现的解决方案更加轻松 . 我做了一个示例方法 . 它准备好了 . 另外,我添加了null和空输入的验证 . 所以这个方法现在完全是防弹的您可以使用TryParse来确定字符串是否可以解析为整数 .
布尔值会告诉你它是否有效 .
这是C#方法 . Int.TryParse Method (String, Int32)
Update 从C#7开始:
var可以用它们各自的类型代替!
我知道这是一个旧线程,但没有一个答案真的为我做了 - 要么低效,要么没有封装以便于重用 . 我还想确保如果字符串为空或null,则返回false . TryParse返回在这种情况下为true(空字符串在解析为数字时不会导致错误) . 所以,这是我的字符串扩展方法:
使用简单:
或者,如果要测试其他类型的数字,可以指定“样式” . 因此,要使用Exponent转换数字,您可以使用:
或者要测试潜在的十六进制字符串,您可以使用:
可选的'culture'参数可以以相同的方式使用 .
它受限于无法转换太大而不能包含在double中的字符串,但这是一个有限的要求,我认为如果您使用的数字大于此值,那么您可能需要额外的专门数字处理无论如何功能 .
如果
input
是所有数字,则返回true . 唐't know if it' s比TryParse
好,但它会起作用 .如果您只想知道它是否有一个或多个数字与字符混合,请不要使用
^
+
和$
.Edit: 实际上我认为它比TryParse更好,因为很长的字符串可能会溢出TryParse .
我已多次使用此功能:
但你也可以使用;
从Benchmarking IsNumeric Options
alt text http://aspalliance.com/images/articleimages/80/Figure1.gif
alt text http://aspalliance.com/images/articleimages/80/Figure2.gif
如果您想要捕获更广泛的数字,例如PHP的is_numeric,您可以使用以下内容:
单元测试:
请记住,仅仅因为值是数字并不意味着它可以转换为数字类型 . 例如,
"999999999999999999999999999999.9999999999"
是一个perfeclty有效数值,但它不适合.NET数字类型(不是标准库中定义的那个) .如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个) .
没有正则表达式和
尽可能使用Microsoft的代码
你也可以这样做:
这将照顾通常的恶意:
开头减去( - )或加号()
包含十进制字符BigIntegers不会解析带小数点的数字 . (所以:
BigInteger.Parse("3.3")
会抛出异常,而TryParse
会返回false)没有搞笑的非数字
涵盖数量大于
Double.TryParse
的通常使用情况你必须添加对
System.Numerics
的引用并且在你的 class 之上有using System.Numerics;
(好吧,第二个是我想的奖金:)