Java string to float

This article will example how to convert a string to float in java in following 3 ways

  • Float.parseFloat() method
  • Float.valueOf() method, and
  • Float constructor.

Remember that string value should be parseable to float format, else none of these methods will work.

Method 1: Using Float.parseFloat()
java.lang.Float is a wrapper class around float primitive type. It contains parseFloat() method to convert a string to float.

accepts a string argument and returns a float primitive whose value is the same as string.

parseFloat() is a static method, so it can be invoked using the class. Example,

String s = "12.5";
// convert string to float
float f = Float.parseFloat(s);

parseFloat() may throw

  1. NullPointerException if the string is null.
  2. NumberFormatException, if the string is not in valid float format such as “abcd”, “24.rt”, “12%”, “67$” etc.

Method 2: Using Float.valueOf()
valueOf() is another static method in java.lang.Float class which accepts a string and converts it to float. Example,

String s = "12.5";
// convert string to float 
Float f = Float.valueOf(s);

Note that valueOf() returns an object of Float class rather than primitive float.

valueOf() throws NumberFormatException, if the string is not parseable to float.
Though it can be used in place of float primitive due to unboxing but if you still want it as primitive, then convert the Float object to primitive using floatValue() as shown below

String s = "12.5"; 
// convert string to float 
float f = Float.valueOf(s).floatValue();

Method 3: Using Float constructor
java.lang.Float class has a constructor which takes a string value and creates a Float object with value of this string converted to float. Example,

String s = "12.5"; 
// create Float object from string
Float fOb = new Float(s);
// convert to primitive 
float f = fOb.floatValue();

Float constructor internally invokes parseFloat() for converting string to float value.

Float constructor has been deprecated since Java 9 and you should use parseFloat() or valueOf() methods to convert string to float.

Hope the article was useful.

Liked the article ? Spread the word...