How to convert a Java String to a float

Java String/float FAQ: How do I convert a Java String to a float?

Converting a String to a float requires that you first convert the String to a Float object, then convert the Float object to a float data type (Float is an object, while float is a primitive data type).

An example of a simple program that performs this conversion is shown below:

public class StringToFloat

  public static void main (String[] args)

    // String s = "fred";    // do this if you want an exception

    String s = "100.00";

      float f = Float.valueOf(s.trim()).floatValue();
      System.out.println("float f = " + f);
    catch (NumberFormatException nfe)
      System.out.println("NumberFormatException: " + nfe.getMessage());

Other notes

  • Float.toString(float f) is used to convert in the other direction, from a float to a String.



we can use like this ..

its easy to use also....

float f = Float.parseFloat(s);
System.out.println("float f = " + f);

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.