How to check if a String is numeric in Java

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

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

相关标签:
30条回答
  • 2020-11-21 05:47

    if you are on android, then you should use:

    android.text.TextUtils.isDigitsOnly(CharSequence str)
    

    documentation can be found here

    keep it simple. mostly everybody can "re-program" (the same thing).

    0 讨论(0)
  • 2020-11-21 05:47

    I think the only way to reliably tell if a string is a number, is to parse it. So I would just parse it, and if it's a number, you get the number in an int for free!

    0 讨论(0)
  • 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;
        }
    
    0 讨论(0)
  • 2020-11-21 05:48

    You can use NumberFormat#parse:

    try
    {
         NumberFormat.getInstance().parse(value);
    }
    catch(ParseException e)
    {
        // Not a number.
    }
    
    0 讨论(0)
  • 2020-11-21 05:48

    Here is my class for checking if a string is numeric. It also fixes numerical strings:

    Features:

    1. Removes unnecessary zeros ["12.0000000" -> "12"]
    2. Removes unnecessary zeros ["12.0580000" -> "12.058"]
    3. Removes non numerical characters ["12.00sdfsdf00" -> "12"]
    4. Handles negative string values ["-12,020000" -> "-12.02"]
    5. Removes multiple dots ["-12.0.20.000" -> "-12.02"]
    6. No extra libraries, just standard Java

    Here you go...

    public class NumUtils {
        /**
         * Transforms a string to an integer. If no numerical chars returns a String "0".
         *
         * @param str
         * @return retStr
         */
        static String makeToInteger(String str) {
            String s = str;
            double d;
            d = Double.parseDouble(makeToDouble(s));
            int i = (int) (d + 0.5D);
            String retStr = String.valueOf(i);
            System.out.printf(retStr + "   ");
            return retStr;
        }
    
        /**
         * Transforms a string to an double. If no numerical chars returns a String "0".
         *
         * @param str
         * @return retStr
         */
        static String makeToDouble(String str) {
    
            Boolean dotWasFound = false;
            String orgStr = str;
            String retStr;
            int firstDotPos = 0;
            Boolean negative = false;
    
            //check if str is null
            if(str.length()==0){
                str="0";
            }
    
            //check if first sign is "-"
            if (str.charAt(0) == '-') {
                negative = true;
            }
    
            //check if str containg any number or else set the string to '0'
            if (!str.matches(".*\\d+.*")) {
                str = "0";
            }
    
            //Replace ',' with '.'  (for some european users who use the ',' as decimal separator)
            str = str.replaceAll(",", ".");
            str = str.replaceAll("[^\\d.]", "");
    
            //Removes the any second dots
            for (int i_char = 0; i_char < str.length(); i_char++) {
                if (str.charAt(i_char) == '.') {
                    dotWasFound = true;
                    firstDotPos = i_char;
                    break;
                }
            }
            if (dotWasFound) {
                String befDot = str.substring(0, firstDotPos + 1);
                String aftDot = str.substring(firstDotPos + 1, str.length());
                aftDot = aftDot.replaceAll("\\.", "");
                str = befDot + aftDot;
            }
    
            //Removes zeros from the begining
            double uglyMethod = Double.parseDouble(str);
            str = String.valueOf(uglyMethod);
    
            //Removes the .0
            str = str.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");
    
            retStr = str;
    
            if (negative) {
                retStr = "-"+retStr;
            }
    
            return retStr;
    
        }
    
        static boolean isNumeric(String str) {
            try {
                double d = Double.parseDouble(str);
            } catch (NumberFormatException nfe) {
                return false;
            }
            return true;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 05:51

    // please check below code

    public static boolean isDigitsOnly(CharSequence str) {
        final int len = str.length();
        for (int i = 0; i < len; i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题