Java string to number method: 1. Convert to integer number [Integer.parseInt(String s)]; 2. Convert to floating point number [Float.parseFloat(String s)].
Related free learning recommendations: java basic tutorial
java string Method of converting numbers:
1. Convert to integer numbers
(1) Integer.parseInt(String s), the code example is as follows:
public class Test { public static void main(String args[]){ String s = "123"; int num = Integer.parseInt(str); int sum = num + 100; System.out.println("Result is: "+sum); // 输出结果为:Result is: 223 }}
(2) Integer.valueOf(String s), the code example is as follows:
public class Test2 { public static void main(String args[]){ String s = "-100"; int num = Integer.valueOf(str); int sum = num + 101; System.out.println("Result is: "+sum); // 输出结果为:Result is: 1 } }
2, Convert to floating point number
(1) Float.parseFloat(String s), the code example is as follows:
public class Test { public static void main(String args[]){ String s = "123.11"; float num = Float.parseFloat(s); float sum = num + 100; System.out.println("Result is: "+sum); // 输出结果为:Result is: 223.11 }}
(2) Double .parseDouble(String s), the code example is as follows:
public class Test2 { public static void main(String args[]){ String s = "100.01"; double num = Double.parseDouble(s); double sum = num + 100; System.out.println("Result is: "+sum); // 输出结果为:Result is: 200.01 }}
The specific code required in the question to convert String s="00000123" into 123 is as follows:
public class Test { public static void main(String args[]){ String s = "00000123"; int num = Integer.parseInt(s); System.out.println("Result is: "+num); // 输出结果为:Result is: 123 }}
Extended information:
1. Convert integer and floating point types to strings in Java:
public class Test { public static void main(String args[]){ int i = 11; String s = i + ""; // 方法一 String s = String.valueOf(i); // 方法二 String s = Integer.toString(i); // 方法三 } }
2. Determine whether a string is a number in Java:
public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ if (!Character.isDigit(str.charAt(i))){ return false; } } return true; }
The above is the detailed content of How to convert string to number in java. For more information, please follow other related articles on the PHP Chinese website!