How to check if a string is numeric in Java

4 Answers

0 votes
public class MyClass {
    public static boolean isNumeric(String s) {
	    if (s == null) {
	        return false;
	    }
	    try {
	        double d = Double.parseDouble(s);
	    } catch (NumberFormatException e) {
	        return false;
	    }
	    return true;
	}
    
    public static void main(String args[]) {
        System.out.println((isNumeric("989762") == true) ? "yes" : "no");
        System.out.println((isNumeric("3.14") == true) ? "yes" : "no");
        System.out.println((isNumeric("-298") == true) ? "yes" : "no");
        System.out.println((isNumeric("12W") == true) ? "yes" : "no");
    }
}



/*
run:

yes
yes
yes
no

*/

 



answered Jul 25, 2020 by avibootz
0 votes
import java.util.regex.Pattern;

public class MyClass {
    private static Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
    
    public static boolean isNumeric(String s) {
	    if (s == null) {
	        return false;
	    }
	    return pattern.matcher(s).matches();
	}
    
    public static void main(String args[]) {
        System.out.println((isNumeric("989762") == true) ? "yes" : "no");
        System.out.println((isNumeric("3.14") == true) ? "yes" : "no");
        System.out.println((isNumeric("-298") == true) ? "yes" : "no");
        System.out.println((isNumeric("12W") == true) ? "yes" : "no");
    }
}



/*
run:

yes
yes
yes
no

*/

 



answered Jul 25, 2020 by avibootz
0 votes
public class MyClass {
    public static boolean isNumeric(String str) {
        boolean isNumeric = true;
         
        try {
            Double.parseDouble(str);
        } catch (NumberFormatException e) {
                isNumeric = false;
        }
         
        return isNumeric;
    }
     
    public static void main(String args[]) {
        String str = "203874";
         
        System.out.println(isNumeric(str));
    }
}
     
     
     
     
/*
run:
     
true
     
*/

 



answered Nov 30, 2023 by avibootz
0 votes
public class MyClass {
    public static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");
    }
    
    public static void main(String args[]) {
        String str = "203874";
        
        System.out.println(isNumeric(str));
    }
}
    
    
    
    
/*
run:
    
true
    
*/

 



answered Nov 30, 2023 by avibootz

Related questions

2 answers 166 views
2 answers 165 views
2 answers 143 views
3 answers 219 views
3 answers 199 views
3 answers 318 views
3 answers 185 views
185 views asked Mar 28, 2023 by avibootz
...