How to check if a String is numeric in Java

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

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

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 05:48

    We can try replacing all the numbers from the given string with ("") ie blank space and if after that the length of the string is zero then we can say that given string contains only numbers. Example:

    boolean isNumber(String str){
            if(str.length() == 0)
                return false; //To check if string is empty
            
            if(str.charAt(0) == '-')
                str = str.replaceFirst("-","");// for handling -ve numbers
        
            System.out.println(str);
            
            str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points
            
            if(str.length() == 0)
                return false; // to check if it is empty string after removing -ve sign and decimal point
            System.out.println(str);
            
            return str.replaceAll("[0-9]","").length() == 0;
        }
    

提交回复
热议问题