Java String to number FAQ: How do I convert a String to a number in Java?
You convert a Java String to a number using the methods of the class whose type you want to convert to. For instance, if you want to try to convert a String to an int, you use the parseInt() method of the Java Integer class, like this:
String pageNumString = "5"; int pageNum = 0; try { // perform the string to int conversion here pageNum = Integer.parseInt(pageNumString); } catch (NumberFormatException nfe) { // do something with the exception }
You do the same thing with the Java Float class (Float.parseFloat(String), the Java Double class (Double.parseDouble(String)), and so on.
As you can see from the source code, the thing you have to deal with here is the possible NumberFormatException. If someone gives you a String like "fred", and you try to convert that to an int, it's going to throw a NumberFormatException, so you have to catch that exception and deal with it. (Or, the Java method you're writing can alternatively throw the NumberFormatException without dealing with it, but either way, someone will have to handle it.)
Java String to number examples: Related links
I hope these examples of how to convert Java Strings to numbers has been helpful. There is much more content related to Java and the String class on the blog, including these posts:
- A Java toString method that uses reflection to dynamically print class fields
- Use String.format to format a Java String
- A cheat sheet (reference page) for printf format specifiers
- How to convert a Java String to an int
- How to create an array of Strings (or any object) in Java
- A method to return the longest String in a given array of Strings