我可以确定字符串是否可以转换为数字值? [英] As I can determining if string can be turned to a numerico value?

查看:63
本文介绍了我可以确定字符串是否可以转换为数字值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我可以确定字符串是否可以转换为数字值?因为

包含alfanumeric数据它会向我返回错误。

因为我可以避免以下错误?


String str =" 123";

int valInt = Convert.ToInt32(str); // OK

String str =" StringXX"

int valInt = Convert.ToInt32(str); // ERROR

As I can determining if string can be turned to a numerico value?, since to
contain alfanumeric data it returns an error to me.
as I can avoid the following error?

String str="123";
int valInt = Convert.ToInt32(str); //OK
String str="StringXX"
int valInt = Convert.ToInt32(str); //ERROR

推荐答案

在2.0框架中,查找TryParse方法....否则,

最简单方法(不一定是最快的)是在异常处理程序中包装

转换。

Daniel R. Rossnagel写道:
In the 2.0 framework, look for the TryParse method .... otherwise, the
easiest approach (not necessarily the most speedy) is to wrap the
convert in an exception handler.
Daniel R. Rossnagel wrote:
作为我可以确定字符串是否可以转换为数字值?,因为要包含alfanumeric数据,它会向我返回错误。
因为我可以避免以下错误?

字符串str =" 123";
int valInt = Convert.ToInt32(str); // OK
String str =" StringXX"
int valInt = Convert.ToInt32(str); //错误
As I can determining if string can be turned to a numerico value?, since to
contain alfanumeric data it returns an error to me.
as I can avoid the following error?

String str="123";
int valInt = Convert.ToInt32(str); //OK
String str="StringXX"
int valInt = Convert.ToInt32(str); //ERROR



使用正则表达式是最经济有效的方法。


private static Regex _isNumber = new Regex(@" ^ \d +
Using Regular expressions is the most cost effective way.

private static Regex _isNumber = new Regex(@"^\d+


");


public static bool IsInteger(string theValue)

{

匹配m = _isNumber.Match(theValue);

返回m.Success;

} // IsInteger




如果您没有找到符合您口味的话,请使用此


public bool IsNumeric(string s)

{

试试{

Int32.Parse(s);

}

抓住{

返回false;

}

返回true;

}

HTH,


Denis

" Daniel R. Rossnagel" <博士********* @ hotmail.com>在消息中写道

新闻:%2 **************** @ TK2MSFTNGP14.phx.gbl ...
");

public static bool IsInteger(string theValue)
{
Match m = _isNumber.Match(theValue);
return m.Success;
} //IsInteger

OR
If you dont find that to your taste use this

public bool IsNumeric(string s)
{
try {
Int32.Parse(s);
}
catch {
return false;
}
return true;
}
HTH,

Denis
"Daniel R. Rossnagel" <dr*********@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
正如我可以确定字符串是否可以转换为数字值?,因为
包含alfanumeric数据它会向我返回错误。
因为我可以避免以下错误?

字符串str =" 123";
int valInt = Convert.ToInt32(str); // OK
String str =" StringXX"
int valInt = Convert.ToInt32(str); //错误
As I can determining if string can be turned to a numerico value?, since to contain alfanumeric data it returns an error to me.
as I can avoid the following error?

String str="123";
int valInt = Convert.ToInt32(str); //OK
String str="StringXX"
int valInt = Convert.ToInt32(str); //ERROR



这篇关于我可以确定字符串是否可以转换为数字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆