Home> Java> javaTutorial> body text

How to convert string to number in java

DDD
Release: 2023-08-11 11:34:24
Original
15643 people have browsed it

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.

How to convert string to number in java

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!