Java String to Float

Posted in /  

Java String to Float
ramyashankar

Ramya Shankar
Last updated on March 29, 2024

    Many beginners want to know how to convert Java String to Java float. All String operations are easy in Java, and there are many utility methods. Java 6 onwards also has Float objects instead of the primitive float type, making float manipulations easier.

    How to convert Java String to float

    We will show an example to convert Java String to Java float and also handle possible exceptions.

    String str = "3.14f";
    Float flObj = Float.valueOf(str);
    System.out.println(flObj);

    Note that you will get the same result without the ‘f’ too. If you want the primitive float type, you have to use the floatValue() method:

    float flval = flObj.floatValue();
    System.out.println(flval);

    Strings may have some white spaces, especially when the data is obtained from external sources, so it is good to trim the string before applying the conversion methods:

    String str = "     3.14";
    Float flObj = Float.valueOf(str.trim());

    If the String is anything other than a float, the program will throw a java.lang.NumberFormatException, which should be handled by the developer for the program to exit gracefully.

    String str = "     3.14    5";
    try{
    Float flObj = Float.valueOf(str.trim());
    float flval = flObj.floatValue();
    System.out.println(flval);
    }catch(NumberFormatException nme)
    {
    System.out.println("Enter a valid float");
    }

    If we enter long, int, double values in the String, the result will be converted to float and displayed:

    String str = "34234234234233";

    Converting this will yield 3.42342343E13 as the answer. You can try the same with int, double, etc. Another way to convert Java String to float, the primitive type directly is using the parseFloat() method:

    String str = "3423423423423.334453453454";
    float flParse = Float.parseFloat(str);
    System.out.println(flParse);

    The exception handling is the same with the parseFloat() method as well. If you use an IDE for coding, you can see the description, which will have details of the return type, exceptions thrown, parameters, and usage.

    Conclusion

    There are similar conversion methods for converting String to int, long, double as well. These are parseInt(), parseLong() and parseDouble() respectively. Other than that, there are valueOf() methods too.

    People are also reading:

    Leave a Comment on this Post

    0 Comments