首先看不安全的方法:
String转Int:
public class Test{
public static void main(String [] args){
System.out.println("result = "+(Integer.parseInt("123456") + 654321));
}
}
String转Double:
public class Test{
public static void main(String [] args){
String str = "0.123456";
System.out.println("result = "+(Double.valueOf(str).doubleValue() + 0.654321));
}
}
如果是生产环境,还需要异常处理:
public class Test{
public static void main(String [] args){
String str = "0.123456";
try{
System.out.println("result = "+(Double.valueOf(str).doubleValue() + 0.654321));
}
catch(NumberFormatException ec){
ec.printStackTrace();
//other logic
}
}
}