Home >Java >javaTutorial >How to convert string to number in java
Java method to convert a string to a number: 1. Use the Integer.parseInt() method to convert the string to an integer; 2. Use the Double.parseDouble() method to convert the string to a floating point number; 3. Use the Float.parseFloat() method to convert the string to a floating point number; 4. Use the Long.parseLong() method to convert the string to a long integer; 5. Use the Short.parseShort() method to convert the string to a short integer.
In Java, you can use the following methods to convert strings to numbers:
Use the Integer.parseInt() method to convert characters Convert string to integer:
String str = "123"; int num = Integer.parseInt(str); System.out.println(num); // 输出:123
Use Double.parseDouble() method to convert string to floating point number:
String str = "3.14"; double num = Double.parseDouble(str); System.out.println(num); // 输出:3.14
Use Float.parseFloat() method to convert string to floating point number:
String str = "2.5"; float num = Float.parseFloat(str); System.out.println(num); // 输出:2.5
Use the Long.parseLong() method to convert a string to a long integer:
String str = "1000000000"; long num = Long.parseLong(str); System.out.println(num); // 输出:1000000000
Use the Short.parseShort() method to convert a string to a short integer:
String str = "10"; short num = Short.parseShort(str); System.out.println(num); // 输出:10
It should be noted that if the string cannot be converted to a number, a NumberFormatException will be thrown. So before converting, it's a good idea to do some validation to make sure the string can be converted to a number correctly.
In addition, you can also use regular expressions or other methods to process the string, such as removing spaces, special characters, etc., to ensure the validity of the string.
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!