How to Convert String to float in Java

How to Convert String to Float in java

It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float in the following ways:

  • Convert using Float.parseFloat() method
  • Convert using Float.valueOf() method
  • Convert using constructor new Float(String).floatValue()

Convert using Float.parseFloat()

The parseFloat() is the static method of Float class parses the String argument and returns a float value. The value that method returns is not an instance of Float class; it just a primitive float value. This is the most common and popular method to convert String to float. The signature of the parseFloat() method is given below:

The parameter s will be converted to a primitive float value.

Example

In the following example, str is a variable of type String having value “89.67”. f is a variable of float type that stores the converted value of str. Float is a wrapper class. The parseFloat() is a static method passing str as an argument to it and returns float value. The println statement prints the converted value of str.

Output

Remember: All characters must be in digits; the number can have a minus sign.

Valid Conversion

  • String number=”-23.67”;
  • String number=”23.67”;

Invalid Conversion

  • String number=”369.90a”;
  • String number=” a 369.90”;

If you defines a String as above, Float.parseFloat() throws “NumberFormatException,” because it is not a valid conversion. 

Convert using Float.valueOf() method

The Float.valueOf() is a static method that returns a Float object holding the value of the specified String. The value that method returns is an instance of Float class not a primitive type. The signature of the method is given below-

Example

Consider the example, avg is a variable of type String having value “225.92”. num is a variable of float type that stores the converted value of str. Float is a wrapper class. The Float.valueOf() is a static method passing avgas an argument to it and returns a float value. The println statement prints the converted value of num.

Output

Convert using constructor new Float(String).floatValue()

It is an alternative method is to create an instance of Float class and then invoke it’s floatValue() method. You can create constructor in the following ways:

You can also write above code as: 

Or

Example 

Consider the example, val is a variable of type String having value “876.234”. num is a variable of float type that stores the converted value of val. The new is a keyword that creates the constructor of the Float class. It has a val as an argument passing to it. It invokes the float.value() method of the Float class. The println statement prints the converted value of num.

Output