Convert String to float in Java

Tags: String float Convert

In this Java core tutorial, we learn how to convert String value into float value in Java via different solutions.

Parse a String to float using Float.parseFloat() method

ConvertStringToFloatExample1.java

public class ConvertStringToFloatExample1 {
    public static void main(String[] args) {
        String value1 = "12.090807";
        float value2 = Float.parseFloat(value1);

        System.out.println("String value: " + value1);
        System.out.println("float value: " + value2);
    }
}
The output is:
String value: 12.090807
float value: 12.090807

Instantiate new float value from a String using Float.valueOf() method

ConvertStringToFloatExample2.java

public class ConvertStringToFloatExample2 {
    public static void main(String[] args) {
        String value1 = "99.0505";
        float value2 = Float.valueOf(value1);

        System.out.println("String value: " + value1);
        System.out.println("float value: " + value2);
    }
}
The output is:
String value: 99.0505
float value: 99.0505

Happy Coding 😊