2013-02-28 51 views
1

我需要一个字符串转换为整型。我的字符串可以是任何类型(float/int/string /特殊字符)。将字符串转换为整数,在C#/。NET

例如:

If my string is "2.3", I need to convert to = 2 
If my string is "anyCharacter", I need to convert to = 0 
If my string is "2", I need to convert to = 2 

我试过如下:

string a = "1.25";int b = Convert.ToInt32(a);  

我得到了错误:

Input string was not in a correct format

如何转换呢?

回答

2

使用Double.TryParse(),一旦你得到它的价值,将其转换为使用Convert.ToInt()int

double parsedNum; 
if (Double.TryParse(YourString, out parsedNum) { 
    newInt = Convert.ToInt32(num); 
} 
else { 
    newInt = 0; 
} 
+0

@K D谢谢:-) – 2013-02-28 09:05:11

1

据我所知,没有任何通用的转换,所以你必须做一个switch找出变量的类型,然后使用以下(每种类型)之一:

int.Parse(string) 

int.TryParse(string, out int) 

第二个将返回一个布尔值,你可以用它来查看是否转换成功或失败。

你最好的选择是使用doubledecimal解析,因为这不会删除任何小数位,不像int

1

我觉得Convert.ToInt32是错误的地方寻找 - 我会用Integer.Tryparse,如果评估的TryParse为假,分配一个0到该变量。在TryParse之前,如果在字符串中找到它,可以简单地删除点后的任何字符。

另外,请记住,有些语言使用“”作为分隔符。

1

尝试:

if (int.TryParse(string, out int)) { 
    variable = int.Parse(string); 
} 
1

尝试之后解析它作为一个浮点数,并转换为整数:

double num; 
if (Double.TryParse(a, out num) { 
    b = (int)num; 
} else { 
    b = 0; 
} 
+1

+1,终于发布了一个正确的答案:D(和其他人开始复制你的代码) – fardjad 2013-02-28 07:51:50

1

这应该有所帮助:将任何字符串看作是double,然后用Math.Floor()将其舍入到最接近的整数。

double theNum = 0; 
string theString = "whatever"; // "2.3"; // "2"; 
if(double.TryParse(theString, out theNum) == false) theNum = 0; 
//finally, cut the decimal part 
int finalNum = (int)Math.Floor(theNum); 

注:if可能不会每本身需要,由于theNum初始化,但它更具可读性这种方式。

0

尝试这样:

public int ForceToInt(string input) 
{ 
    int value; //Default is zero 
    int.TryParse(str, out value); 

    return value; 
} 

这将这样的伎俩。不过,我不建议采取这种方法。无论你得到什么,最好控制你的输入。