Java String to float

In Java, you can convert a String to a float using the Float.parseFloat() method. This method converts a String to a primitive float value.

1. Float.parseFloat()

The Float.parseFloat() method is the most straightforward way to convert a String to a float. If the string is not a valid representation of a float, it will throw a NumberFormatException.

Example:


public class StringToFloatExample {
    public static void main(String[] args) {
        String str = "125.75";
        
        // Convert String to float using parseFloat()
        float num = Float.parseFloat(str);
        
        System.out.println("Converted float: " + num);
    }
}

Output: Converted float: 125.75

Code Explanation:

1. Float.parseFloat(str) converts the string str to a float.

2. If the string is not a valid floating-point number (e.g., “abcd”), it throws a NumberFormatException.

How to handle Exceptions

If the string cannot be converted to a valid float, the Float.parseFloat() method will throw a NumberFormatException. You should handle this exception to avoid program crashes.

Example:


public class StringToFloatExample {
    public static void main(String[] args) {
        String str = "abcd";  // Invalid number string
        
        try {
            float num = Float.parseFloat(str);  // This will throw NumberFormatException
            System.out.println("Converted float: " + num);
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format");
        }
    }
}

Output: Error: Invalid number format

Java String to float – Objective Questions (MCQs)

Q1. Which method is used to convert a string to a float value?






Q2. What will be the output of:

String s = "12.5";
float f = Float.parseFloat(s);
System.out.println(f + 2);






Q3. What is the return type of Float.parseFloat()?






Q4. What happens if the string passed to Float.parseFloat() is not numeric?






Q5. What will "10.0".equals(Float.parseFloat("10.0")) return?






Related Java String to float Topics