java – How can I tell if a string is a number?


I did this, but it seems to me that this approach is somewhat wrong:

private static boolean isDigit(String s) throws NumberFormatException {
    try {
        return true;
    } catch (NumberFormatException e) {
        return false;


As far as I understand, the purpose is to check on Integer ? Then you can:

s.matches("[-+]?\\d+") // для списка из 1 млн целых чисел и не чисел
// (примерно 50/50) эффективность этой строчки практически
// не отличается от описанной в вопросе функции.

If double , but without exponential notation, then


such a regular will do.

Although I would not sweat it and would do exactly the same, only with Double.parseDouble(s) , but I am not an indicator 🙂 And I also noticed the name of the method – it is not very correct, since firstly, there is one in the Character class, and secondly, isNumeric() is appropriate. But these are just comments from the "what do I think about this" series.

Scroll to Top