public class ConvertUtil {
//把String转化为float
public static float convertToFloat(String number, float defaultValue) {
if (TextUtils.isEmpty(number)) {
return defaultValue;
}
try {
return Float.parseFloat(number);
} catch (Exception e) {
return defaultValue;
}
}
//把String转化为double
public static double convertToDouble(String number, double defaultValue) {
if (TextUtils.isEmpty(number)) {
return defaultValue;
}
try {
return Double.parseDouble(number);
} catch (Exception e) {
return defaultValue;
}
}
//把String转化为int
public static int convertToInt(String number, int defaultValue) {
if (TextUtils.isEmpty(number)) {
return defaultValue;
}
try {
return Integer.parseInt(number);
} catch (Exception e) {
return defaultValue;
}
}
---------------------
使用时只需调用上面的方法即可(第二个参数是默认值):
int yeatInt = ConvertUtil.convertToInt("2017",2015);
网友评论