mqp*_*mqp 1082
int n;
bool isNumeric = int.TryParse("123", out n);
Run Code Online (Sandbox Code Playgroud)
从C#7开始更新:
var isNumeric = int.TryParse("123", out int n);
Run Code Online (Sandbox Code Playgroud)
该变种 S可通过它们各自的类型来代替!
Joh*_*ant 350
如果input
是所有数字,则返回true .不知道它是否比TryParse
它好,但它会起作用.
Regex.IsMatch(input, @"^\d+$")
Run Code Online (Sandbox Code Playgroud)
如果你只是想知道它是否有一个或多个数字与字符混合,请不要使用^
+
和$
.
Regex.IsMatch(input, @"\d")
Run Code Online (Sandbox Code Playgroud)
编辑: 实际上我认为它比TryParse更好,因为很长的字符串可能会溢出TryParse.
Kun*_*oel 186
您还可以使用:
stringTest.All(char.IsDigit);
Run Code Online (Sandbox Code Playgroud)
如果输入字符串是任何类型的字母数字,它将返回true
所有数字数字(不是float
)false
.
请注意:stringTest
不应该是空字符串,因为这会通过数字测试.
Nel*_*nda 129
我已多次使用此功能:
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;
}
Run Code Online (Sandbox Code Playgroud)
但你也可以使用;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
Run Code Online (Sandbox Code Playgroud)
替代文字http://aspalliance.com/images/articleimages/80/Figure1.gif
替代文字http://aspalliance.com/images/articleimages/80/Figure2.gif
Eur*_*lli 32
这可能是C#中的最佳选择.
如果您想知道字符串是否包含整数(整数):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
Run Code Online (Sandbox Code Playgroud)
TryParse方法将尝试将字符串转换为数字(整数),如果成功,它将返回true并将相应的数字放在myInt中.如果不能,则返回false.
使用int.Parse(someString)
其他响应中显示的替代方案的解决方案可行,但速度要慢得多,因为抛出异常非常昂贵.TryParse(...)
在版本2中添加到C#语言,直到那时你没有选择.现在你做:你应该避免Parse()
替代方案.
如果要接受十进制数,则十进制类也有一个.TryParse(...)
方法.在上面的讨论中用int替换int,并且适用相同的原则.
The*_*TXI 25
对于许多数据类型,您始终可以使用内置的TryParse方法来查看相关字符串是否会通过.
例.
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
Run Code Online (Sandbox Code Playgroud)
然后结果= True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
Run Code Online (Sandbox Code Playgroud)
结果将= False
BFr*_*ree 20
如果您不想使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
cyb*_*spy 14
我知道这是一个旧线程,但没有一个答案真的为我做了 - 要么效率低,要么没有封装以便于重用.如果字符串为空或null,我还想确保它返回false.在这种情况下,TryParse返回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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用简单:
var mystring = "1234.56789";
var test = mystring.IsNumeric();
Run Code Online (Sandbox Code Playgroud)
或者,如果要测试其他类型的数字,可以指定"样式".因此,要使用Exponent转换数字,您可以使用:
var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);
Run Code Online (Sandbox Code Playgroud)
或者要测试潜在的十六进制字符串,您可以使用:
var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)
Run Code Online (Sandbox Code Playgroud)
可选的'culture'参数可以大致相同的方式使用.
由于无法转换太大而不能包含在double中的字符串而受到限制,但这是一个有限的要求,我认为如果您使用的数字大于此值,那么您可能需要额外的专用数字处理无论如何功能.
JDB*_*JDB 12
如果您想要捕获更广泛的数字,例如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 (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 );
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
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 );
}
Run Code Online (Sandbox Code Playgroud)
请记住,仅仅因为值是数字并不意味着它可以转换为数字类型.例如,"999999999999999999999999999999.9999999999"
是一个perfeclty有效数值,但它不适合.NET数字类型(不是标准库中定义的那个).
Day*_*uiz 12
Kunal Noel 答案的更新
stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.
Run Code Online (Sandbox Code Playgroud)
但是,对于这种情况,我们有空字符串将通过该测试,因此,您可以:
if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
// Do your logic here
}
Run Code Online (Sandbox Code Playgroud)
您可以使用TryParse来确定字符串是否可以解析为整数.
int i;
bool bNum = int.TryParse(str, out i);
Run Code Online (Sandbox Code Playgroud)
布尔值会告诉你它是否有效.
如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个).
你也可以这样做:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
Run Code Online (Sandbox Code Playgroud)
这将照顾通常的恶意:
BigInteger.Parse("3.3")
会抛出异常,并且TryParse
同样会返回false)Double.TryParse
你必须添加一个引用System.Numerics
并且
using System.Numerics;
在你的班级之上(好吧,第二个是我想的奖金:)
我想这个答案只会在所有其他答案之间丢失,但无论如何,这里也是如此.
我通过谷歌结束了对这个问题,因为我想检查,如果string
是numeric
这样我可以只使用double.Parse("123")
了替代TryParse()
方法.
为什么?因为在知道解析是否失败之前必须声明out
变量并检查结果是很烦人的TryParse()
.我想使用的ternary operator
检查,如果string
是numerical
,然后就分析它在第一三元表达或提供第二三元表达式的默认值.
像这样:
var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
Run Code Online (Sandbox Code Playgroud)
它比以下更清洁:
var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
//whatever you want to do with doubleValue
}
Run Code Online (Sandbox Code Playgroud)
我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);
}
Run Code Online (Sandbox Code Playgroud)
例:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
Run Code Online (Sandbox Code Playgroud)
因为IsParseableAs()
尝试将字符串解析为适当的类型而不是仅仅检查字符串是否为"数字",所以它应该是非常安全的.您甚至可以将它用于具有TryParse()
方法的非数字类型,例如DateTime
.
该方法使用反射,你最终调用该TryParse()
方法两次,当然,效率不高,但并不是所有东西都必须完全优化,有时方便更重要.
此方法还可用于轻松地将数字字符串列表解析为double
具有默认值的列表或其他类型,而不必捕获任何异常:
var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
此扩展方法允许您解析具有方法的string
任何方法,并且还允许您指定在转换失败时返回的默认值.type
TryParse()
这比使用上面的扩展方法的三元运算符更好,因为它只进行一次转换.它仍然使用反射......
例子:
"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);
Run Code Online (Sandbox Code Playgroud)
输出:
123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
Run Code Online (Sandbox Code Playgroud)
如果您想知道字符串是否为数字,您可以尝试解析它:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Run Code Online (Sandbox Code Playgroud)
请注意,TryParse
返回a bool
,您可以使用它来检查解析是否成功.
.net 内置函数的最佳灵活解决方案称为- char.IsDigit
。它适用于无限长的数字。如果每个字符都是数字,它只会返回 true。我多次使用它,没有任何问题,而且我找到的解决方案更容易清洁。我做了一个示例方法。它可以使用了。此外,我添加了对 null 和空输入的验证。所以这个方法现在是完全防弹的
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
试试下面的reges
new Regex(@"^\d{4}").IsMatch("6") // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
972969 次 |
最近记录: |