How to check if a String is numeric in Java

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

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

30条回答
  •  情书的邮戳
    2020-11-21 06:07

    // only int
    public static boolean isNumber(int num) 
    {
        return (num >= 48 && c <= 57); // 0 - 9
    }
    
    // is type of number including . - e E 
    public static boolean isNumber(String s) 
    {
        boolean isNumber = true;
        for(int i = 0; i < s.length() && isNumber; i++) 
        {
            char c = s.charAt(i);
            isNumber = isNumber & (
                (c >= '0' && c <= '9') || (c == '.') || (c == 'e') || (c == 'E') || (c == '')
            );
        }
        return isInteger;
    }
    
    // is type of number 
    public static boolean isInteger(String s) 
    {
        boolean isInteger = true;
        for(int i = 0; i < s.length() && isInteger; i++) 
        {
            char c = s.charAt(i);
            isInteger = isInteger & ((c >= '0' && c <= '9'));
        }
        return isInteger;
    }
    
    public static boolean isNumeric(String s) 
    {
        try
        {
            Double.parseDouble(s);
            return true;
        }
        catch (Exception e) 
        {
            return false;
        }
    }
    

提交回复
热议问题