Java Convert String To Float Example

In this article, we will show you how to convert Java String to wrapper Float class or primitive type float code examples. There are different ways we can convert Java String to wrapper Float class or primitive type float. This is a common scenario to convert Java String to wrapper Float class or primitive type float in java programming language.

Java Convert String To Float Example

In this example, we will demonstrate converting Java String to wrapper Float class or primitive type float in 4 ways.
  1. Convert using Float.parseFloat()
  2. Convert using Float.valueOf()
  3. Convert using new Float(String).floatValue()
  4. Convert using DecimalFormat
Please refer the comments in below program are self descriptive.
import java.text.DecimalFormat;
import java.text.ParseException;

 * ConvertStringToFloatExamples
 * @author
public class ConvertStringToFloatExamples {
    public static void main(String[] args) {
        // Convert using Float.parseFloat()
        String numberAsString = "153.25f";
        float number = Float.parseFloat(numberAsString);
        System.out.println("The number is: " + number);
        //Convert using Double.valueOf()
        float number1 = Float.valueOf(numberAsString);
        System.out.println("The number is: " + number1);
        // Convert using new Double(String).doubleValue()
        Float floatObject = new Float(numberAsString);
        float number2 = floatObject.floatValue();
        System.out.println("The number is: " + number2);
        //Convert using DecimalFormat
        DecimalFormat decimalFormat = new DecimalFormat("#");
        try {
             float number3 = decimalFormat.parse(numberAsString).floatValue();
             System.out.println("The number is: " + number3);
        } catch (ParseException e) {
             System.out.println(numberAsString + " is not a valid number.");
Convert using Float.parseFloat() : 153.25
Convert using Double.valueOf() : 153.25
Convert using new Double(String).doubleValue() : 153.25
Convert using DecimalFormat : 153.25

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course