test if string is float java

https‮/:‬/www.lautturi.com
test if string is float java

In Java, you can use the Float.parseFloat method to test if a string can be parsed as a float. The parseFloat method takes a string as an argument and returns the float value represented by the string, or throws a NumberFormatException if the string cannot be parsed as a float.

Here's an example of how to use the Float.parseFloat method to test if a string is a float in Java:

String str = "3.14";

try {
    float f = Float.parseFloat(str);
    System.out.println("The string is a float: " + f);
} catch (NumberFormatException e) {
    System.out.println("The string is not a float.");
}

In this example, the parseFloat method is called on the str string. If the string can be parsed as a float, the float value is printed to the standard output. If the string cannot be parsed as a float, the NumberFormatException is caught and a message is printed to the standard output.

You can find more information about the Float.parseFloat method and how to use it to parse strings as floats in Java in the Java documentation.

Created Time:2017-10-17 20:18:56  Author:lautturi