java
1class TestNumeric {
2 public static boolean isNumeric(String str) {
3 if (str == null) return false;
4 try {
5 Double.parseDouble(str);
6 return true;
7 } catch(NumberFormatException e){
8 return false;
9 }
10 }
11
12 //public static boolean isNumeric(String str) {
13 // if (str == null) return false;
14 // return str.matches("[-+]?\\d+(\\.\\d+)?"); // imcomplete
15 //}
16
17 public static void main(String args[]) {
18 String[] numbers = {
19 "123", "12.3", "-123", "+123", "1abc", "0xFFFF",
20 null, "", " "
21 };
22
23 for (String v : numbers) {
24 System.out.printf("%6s : %b\n", v, isNumeric(v));
25 }
26 }
27}
bash
1$ javac TestNumeric.java && java TestNumeric
2 123 : true
3 12.3 : true
4 -123 : true
5 +123 : true
6 1abc : false
70xFFFF : false
8 null : false
9 : false
10 : false