Java: How to convert strings to numbers

Question: How do I convert a String to an int or a float?

Short answer: You want to use the Integer.parseInt() or Float.parseFloat() methods.

Here’s an example Java program that shows how to convert a String to either an int or a float:

package com.devdaily.javasamples;

public class ConvertStringToNumber {

    public static void main(String[] args) {

        try {
            // string to int
            String s = "5";
            int i = Integer.parseInt(s);
            System.out.println("int value = " + i);

            // string to float
            float f = Float.parseFloat(s);
            System.out.println("float value = " + f);

        } catch (NumberFormatException nfe) {
            System.err.println(nfe.getMessage());
        }

    }

}

As you can see from the sample code, the trick is to use either the parseInt method of the Integer class, or the parseFloat method of the Float class to perform the conversion. As either of these methods can throw a NumberFormatException you should either handle that exception, or let it be thrown by your method.

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.