如何检查字符串是否能够转换为float或int

时间:2016-04-14 06:17:43

标签: java android parsing

我想检查字符串是否能够转换为float或int。

例如:

我收到了

temp = 36.50 

可以使用

将此值转换为float
float Temp = Float.parseFloat(temp);

但是,如果我收到了

temp = 36.#0

我的应用会崩溃。那么如何检查我收到的字符串是否能够转换为float?

对于Int我该怎么做?

2 个答案:

答案 0 :(得分:7)

试试这个

float temp = 0 ;
    try {
    temp = Float.parseFloat(temp);
    } catch (NumberFormatException ex) {
    // Not a float    
    }     
 /*
    you can do something with temp variables in here
 */

答案 1 :(得分:0)

您可以确定String是否为Integer,然后将其转换为避免崩溃或try-catch。

请查看此链接以了解具体方法

Determine if a String is an Integer in Java