In Java, converting a String to a float is done using the parseFloat()
method of the Float
class. This method converts a valid numeric string to its corresponding float
value. If the string cannot be parsed (e.g., if it’s not a valid number), a NumberFormatException
will be thrown. Here’s how to use it:
Example with error handling:
Always ensure the string represents a valid floating-point number to avoid runtime exceptions.