How to check if a string is valid floating point number in Java

1 Answer

0 votes
public class MyClass {

    public static boolean isFloat(String s) {
        try {
            float n = Float.parseFloat(s);
            
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    
    public static void main(String args[]) {
        System.out.println((isFloat("989762") == true) ? "yes" : "no");
        System.out.println((isFloat("3.14") == true) ? "yes" : "no");
        System.out.println((isFloat("-298") == true) ? "yes" : "no");
        System.out.println((isFloat("12W") == true) ? "yes" : "no");
    }
}



/*
run:

yes
yes
yes
no

*/

 



answered Jul 25, 2020 by avibootz
...