C# 如何检查是否为 IsNumeric
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9809340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if IsNumeric
提问by user1202606
Possible Duplicate:
How to identify if string contain a number?
可能的重复:
如何识别字符串是否包含数字?
In VB there's an IsNumeric function, is there something similar in c#?
在VB中有一个IsNumeric函数,在c#中有类似的东西吗?
To get around it, I just wrote the code:
为了解决这个问题,我只写了代码:
if (Int32.Parse(txtMyText.Text.Trim()) > 0)
I was just wondering if there is a better way to do this.
我只是想知道是否有更好的方法来做到这一点。
回答by Corey
回答by Otávio Décio
You could write an extension method:
你可以写一个扩展方法:
public static class Extension
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
回答by MiMo
You should use TryParse- Parsethrows an exception if the string is not a valid number - e.g. if you want to test for a valid integer:
您应该使用TryParse-Parse如果字符串不是有效数字,则抛出异常 - 例如,如果您想测试有效整数:
int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
If you want to test for a valid floating-point number:
如果要测试有效的浮点数:
double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
Note also that Double.TryParsehas an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.
另请注意,Double.TryParse有一个带有额外参数的重载版本,用于指定控制解析过程的各种规则和选项 - 例如本地化('.' 或 ',') - 请参阅http://msdn.microsoft.com/en-us/library/3s27fasw .aspx。
回答by Reinaldo
I think you need something a bit more generic. Try this:
我认为你需要一些更通用的东西。尝试这个:
public static System.Boolean IsNumeric (System.Object Expression)
{
if(Expression == null || Expression is DateTime)
return false;
if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Hope it helps!
希望能帮助到你!
回答by DotNetUser
You should use TryParse method which Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
您应该使用 TryParse 方法,该方法将数字的字符串表示形式转换为其等效的 32 位有符号整数。返回值指示转换是否成功。
int intParsed;
if(int.TryParse(txtMyText.Text.Trim(),out intParsed))
{
// perform your code
}
回答by Scott
There's a slightly better way:
有一个稍微好一点的方法:
int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), out valueParsed))
{ ... }
If you try to parse the text and it can't be parsed, the Int32.Parse method will raise an exception. I think it is better for you to use the TryParse method which will capture the exception and let you know as a boolean if any exception was encountered.
如果您尝试解析文本但无法解析,则 Int32.Parse 方法将引发异常。我认为最好使用 TryParse 方法,该方法将捕获异常并在遇到任何异常时作为布尔值通知您。
There are lot of complications in parsing text which Int32.Parse takes into account. It is foolish to duplicate the effort. As such, this is very likely the approach taken by VB's IsNumeric. You can also customize the parsing rules through the NumberStyles enumeration to allow hex, decimal, currency, and a few other styles.
Int32.Parse 考虑了很多解析文本的复杂性。重复努力是愚蠢的。因此,这很可能是 VB 的 IsNumeric 所采用的方法。您还可以通过 NumberStyles 枚举自定义解析规则,以允许使用十六进制、十进制、货币和其他一些样式。
Another common approach for non-web based applications is to restrict the input of the text box to only accept characters which would be parseable into an integer.
非基于 Web 的应用程序的另一种常见方法是将文本框的输入限制为仅接受可解析为整数的字符。
EDIT: You can accept a larger variety of input formats, such as money values ("$100") and exponents ("1E4"), by specifying the specific NumberStyles:
编辑:通过指定特定的 NumberStyles,您可以接受更多种类的输入格式,例如货币值(“$100”)和指数(“1E4”):
int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowExponent, CultureInfo.CurrentCulture, out valueParsed))
{ ... }
... or by allowing any kind of supported formatting:
...或通过允许任何类型的支持格式:
int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.Any, CultureInfo.CurrentCulture, out valueParsed))
{ ... }
回答by phoog
Other answers have suggested using TryParse, which might fit your needs, but the safest way to provide the functionality of the IsNumericfunction is to reference the VB library and use the IsNumericfunction.
其他答案建议使用TryParse,这可能适合您的需求,但提供该函数功能的最安全方法IsNumeric是引用 VB 库并使用该IsNumeric函数。
IsNumericis more flexible than TryParse. For example, IsNumericreturns truefor the string "$100", while the TryParsemethods all return false.
IsNumeric比 更灵活TryParse。例如,IsNumeric返回truestring "$100",而TryParse所有方法都返回false。
To use IsNumericin C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Informationclass, so assuming you have using Microsoft.VisualBasic;, you can do this:
要IsNumeric在 C# 中使用,请添加对 Microsoft.VisualBasic.dll 的引用。该函数是Microsoft.VisualBasic.Information该类的静态方法,因此假设您有using Microsoft.VisualBasic;,您可以这样做:
if (Information.IsNumeric(txtMyText.Text.Trim())) //...

