Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a string is a number

Short answer

The most reliable way is to try to parse the string and catch NumberFormatException:

boolean isInteger(String text) {
    try {
        Integer.parseInt(text);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
 
void main() {
    IO.println(isInteger("123"));
    IO.println(isInteger("-7"));
    IO.println(isInteger("12a"));
}

Output:

true
true
false

Digits only

If you need digits only, without a sign (for example, an SMS code), a regular expression works:

void main() {
    IO.println("004512".matches("\\d+"));
    IO.println("45.12".matches("\\d+"));
}

Output:

true
false

Decimal numbers

For decimal numbers use Double.parseDouble() or a pattern with an optional fractional part:

void main() {
    String pattern = "-?\\d+(\\.\\d+)?";
 
    IO.println("3.14".matches(pattern));
    IO.println("-10".matches(pattern));
    IO.println("3.".matches(pattern));
}

Output:

true
true
false

Without exceptions or regex

Checking through a stream of characters is fast and easy to read:

void main() {
    String text = "2026";
    boolean digits = !text.isEmpty() && text.chars().allMatch(Character::isDigit);
 
    IO.println(digits);
}

Output:

true

Common mistake

A string of digits may not fit into an int. The regular expression accepts it, but parseInt() fails:

void main() {
    String text = "99999999999";
    IO.println(text.matches("\\d+"));
    IO.println(Integer.parseInt(text));
}

Output:

true
Exception in thread "main" java.lang.NumberFormatException: For input string: "99999999999"

For large values use Long.parseLong() or new BigInteger(text).

Functions used in this recipe

  • Integer.parseInt() — Converts a string containing an integer to an int.
  • String.matches() — Checks whether the whole string matches a regular expression.
  • Character.isDigit() — Checks whether a character is a digit. Related checks are isLetter(), isWhitespace(), isUpperCase().
  • String.chars() — Returns a stream of the character codes of a string.

Thanks for reading!

Donate to the site — we work hard for you.