Java String to number conversions

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;
  // 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:




Thank you so much!! So clear, and you're examples are great! Thanks for covering long too! You are better than the text book. Thank you for existing!

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.