我正在尝试将_string1转换为double,将_string2转换为Int
这个字符串数组是动态生成的。
字符串值可以是空的,也可以是1.1或1或.1,如何处理这个问题。
我试着这样做。
string locale;
locale = System.Web.HttpContext.Current.Request.UserLanguages[0];
CultureInfo culture;
culture = new CultureInfo(locale);
double cValue = Double.Parse(_string[1], culture.NumberFormat)
int sValue = Int32.Parse(_string[2], culture.NumberFormat)这有时会在有空字符串或十进制字符串时给出无效的输入。
发布于 2012-03-16 21:51:05
对于double,您可以使用这样的三元操作符
double d = Double.TryParse(_string[1], out d) ? Convert.ToDouble(_string[1]) : 0;为了使其安全,您可以使用尝试捕获或Double.TryParse方法,这是一个更好的选择。
如果您想要显示这一点,您将得到0作为输出。您可以用下面的行将其转换为0.00
string output = (String.Format("{0:0.00}", cValue));发布于 2012-03-16 21:32:17
您可以使用double.TryParse。
// There's no need to initialize cValue since it's used as an
// out parameter by TryParse which guarantees initialization.
// If TryParse fails the output parameter will be set it to
// default(T), where T is double in this case, i.e. 0.
double cValue;
if( Double.TryParse( line[8], out cValue ) )
{
// success (cValue is now the parsed value)
}
else
{
// failure (cValue is now 0)
}或者如果您需要指定区域性
if(double.TryParse(line[8], NumberStyles.Any, CultureInfo.CurrentCulture, out cValue))
{
}如果你真的想简明扼要,那么你可以简单地使用以下几个词:
double cValue;
Double.TryParse( line[8], out cValue );上面的额外线条只是为了演示。
发布于 2012-03-16 21:30:22
试试这个..。
double cValue = 0.0;
int sValue = 0;
if(!String.IsNullOrEmpty(_string[1]))
{
cValue = Convert.ToDouble(_string[1]);
}
if (!String.IsNullOrEmpty(_string[2]))
{
sValue = Convert.ToInt32(_string[2]);
} http://msdn.microsoft.com/en-us/library/zh1hkw6k.aspx
如果您的字符串为空或空,它将不会尝试转换它。它将只是0.0或0。
https://stackoverflow.com/questions/9744703
复制相似问题