The method parseFloat(String s) just parse the String input s and eventually return a Float object. As you would have noticed, the String method argument should be a number which means it should be consists by our counting numbers. It is understood that the string input should be consisting of decimal numbers only otherwise invoking the Float.parseFloat method would throw a NumberFormatException.Let’s take the following code snippet:
Float fValue= Float.parseFloat("103");
The above code result will give an output of 103. As you would have noticed, we just convert the string “103” into a Float object using the static method Float.parseFloat. You might be wondering what if we put a letter or any other characters beside numbers. The method parseFloat would throw NumberFormatException. Like for this example:
Running the above code would result to:
Exception in thread "main" java.lang.NumberFormatException: For input string: "A"
The above exception will be encountered if the input is not a recognizable value by Float class. If we are asking for a user input, it might be good to catch this exception and return a more user-friendly message.
Java Float.parseFloat maximum and minimum value
There is always a limit on what we could parse. You might be wondering how to determine the maximum and minimum value that is allowable by the parseFloat method. Well getting the threshold is quite easy and can be determine by using the two static values available in Float class which is the following:
Let’s take an example that crosses the minimum and maximum value that we could parse using the Float.parseFloat java method:
Running the above code would result to the following: