How to convert String to float in Java

  • 13 October 2016
  • ADM

 

How to convert String to float in Java - images/logos/java.jpg

 

To convert a String to float in Java you have two simple options using the static methods from Float class:

  • Float.parseFloat(String s): returns a primitive float value;
  • Float.valueOf(String s): returns an Float object.

Ignoring any of the exceptions that can be thrown, all you need to do to convert a String to float is, use on of this lines of code:

float val1 = Float.parseFloat(value);
float val2 = Float.valueOf(value);

or

Float obj = Float.valueOf(value);

Note: even if the valueOf method is returning an Float object you can use the primitive float because the boxing and unboxing will be done automatically.

Example

package com.admfactory;

public class FloatConverter {

    public static void main(String[] args) {
	// String value = "2000.02d";
	// String value = "2000.02f";
	String value = "3000.03";
	/** Use the value to see the exceptions */
	// String value = "number";

	try {
	    float val1 = Float.parseFloat(value);
	    System.out.println("val1: " + val1);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    float val2 = Float.valueOf(value);
	    System.out.println("val2: " + val2);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    Float obj = Float.valueOf(value);
	    System.out.println("obj:  " + obj);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}
    }
}

Output

If the value string is a valid float like "1", "2", and so on, it will be converted to a Java primitive float with no problem. The output for this will be:

val1: 3000.03
val2: 3000.03
obj:  3000.03

otherwise, if it fails for any reason, the conversion can throw a NumberFormatException, so to capture and deal with the possible error the code need to be used in try/catch block as shown in the example. The output for this case will be:

java.lang.NumberFormatException: For input string: "number"
 at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
 at java.lang.Float.parseFloat(Float.java:452)
 at com.admfactory.xml.FloatConverter.main(FloatConverter.java:13)

Note that values like 2000.02d or 2000.02f are valid float values.

 

References