1.将String转化为Int
在 Java 中要将 String 类型转化为 int 类型时,需要使用 Integer 类中的 parseInt() 方法或者 valueOf() 方法进行转换.
方法一:
String str = "123";
try {
int a = Integer.parseInt(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
方法二:
String str = "123";
try {
int b = Integer.valueOf(str).intValue()
} catch (NumberFormatException e) {
e.printStackTrace();
}
2.将String转换为Float
public class Main {
public static void main(String args[]) {
String str = "1234.587878f";
//variable to store result
float result = 0;
//converting string to Float
//method 1
result = Float.valueOf(str).floatValue();
System.out.println("result (value of str as float) = " + result);
//method 2
result = Float.parseFloat(str);
System.out.println("result (value of str as float) = " + result);
}
}
静态parseXXX方法(转换String)
String s = “1”;
byte b = Byte.parseByte( s );
short t = Short.parseShort( s );
int i = Integer.parseInt( s );
long l = Long.parseLong( s );
Float f = Float.parseFloat( s );
Double d = Double.parseDouble( s );