How to check if a String is numeric in Java

前端 未结 30 3279
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  轮回少年
    2020-11-21 05:52

    Exceptions are expensive, but in this case the RegEx takes much longer. The code below shows a simple test of two functions -- one using exceptions and one using regex. On my machine the RegEx version is 10 times slower than the exception.

    import java.util.Date;
    
    
    public class IsNumeric {
    
    public static boolean isNumericOne(String s) {
        return s.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.      
    }
    
    public static boolean isNumericTwo(String s) {
        try {
            Double.parseDouble(s);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    public static void main(String [] args) {
    
        String test = "12345.F";
    
        long before = new Date().getTime();     
        for(int x=0;x<1000000;++x) {
            //isNumericTwo(test);
            isNumericOne(test);
        }
        long after = new Date().getTime();
    
        System.out.println(after-before);
    
    }
    
    }
    

提交回复
热议问题