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