How to check if a String is numeric in Java

2018-12-31 01:02发布

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

30条回答
无色无味的生活
2楼-- · 2018-12-31 01:56

// 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;
}
查看更多
明月照影归
3楼-- · 2018-12-31 01:56

If you guys using the following method to check:

public static boolean isNumeric(String str) {
    NumberFormat formatter = NumberFormat.getInstance();
    ParsePosition pos = new ParsePosition(0);
    formatter.parse(str, pos);
    return str.length() == pos.getIndex();
}

Then what happend with the input of very long String, such as I call this method:

System.out.println(isNumeric("94328948243242352525243242524243425452342343948923"));

The result is "true", also it is a too-large-size number! The same thing will happen if you using regex to check! So I'd rather using the "parsing" method to check, like this:

public static boolean isNumeric(String str) {
    try {
        int number = Integer.parseInt(str);
        return true;
    } catch (Exception e) {
        return false;
    }
}

And the result is what I expected!

查看更多
何处买醉
4楼-- · 2018-12-31 01:57

Regex Matching

Here is another example upgraded "CraigTP" regex matching with more validations.

public static boolean isNumeric(String str)
{
    return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}
  1. Only one negative sign - allowed and must be in beginning.
  2. After negative sign there must be digit.
  3. Only one decimal sign . allowed.
  4. After decimal sign there must be digit.

Regex Test

1                  --                   **VALID**
1.                 --                   INVALID
1..                --                   INVALID
1.1                --                   **VALID**
1.1.1              --                   INVALID

-1                 --                   **VALID**
--1                --                   INVALID
-1.                --                   INVALID
-1.1               --                   **VALID**
-1.1.1             --                   INVALID
查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 01:57

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. [If you found this answer helpful then please do consider up voting it] Example:

boolean isNumber(String str){
       return str.replaceAll("[0-9]","").length() == 0;
}
查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 02:00

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;
    }

}
查看更多
人间绝色
7楼-- · 2018-12-31 02:01

Google's Guava library provides a nice helper method to do this: Ints.tryParse. You use it like Integer.parseInt but it returns null rather than throw an Exception if the string does not parse to a valid integer. Note that it returns Integer, not int, so you have to convert/autobox it back to int.

Example:

String s1 = "22";
String s2 = "22.2";
Integer oInt1 = Ints.tryParse(s1);
Integer oInt2 = Ints.tryParse(s2);

int i1 = -1;
if (oInt1 != null) {
    i1 = oInt1.intValue();
}
int i2 = -1;
if (oInt2 != null) {
    i2 = oInt2.intValue();
}

System.out.println(i1);  // prints 22
System.out.println(i2);  // prints -1

However, as of the current release -- Guava r11 -- it is still marked @Beta.

I haven't benchmarked it. Looking at the source code there is some overhead from a lot of sanity checking but in the end they use Character.digit(string.charAt(idx)), similar, but slightly different from, the answer from @Ibrahim above. There is no exception handling overhead under the covers in their implementation.

查看更多
登录 后发表回答