0

I am searching for a method to check if it is possible to convert a string to int.

The following link says that it is not possible but since new Java version are available I would like to check.

Community
  • 1
  • 1
user3541377
  • 31
  • 1
  • 8

3 Answers3

4

You may wish to consider the NumberUtils.isDigits method from Apache Commons. It gives a boolean answer to the question and is null safe.

For a broader range of numbers that could include decimal points such as float or double, use NumberUtils.isParsable.

Erica Kane
  • 3,137
  • 26
  • 36
3

Java 8 does not change anything by the type parsing. So you still have write your own typeParser like this:

public Integer tryParse(String str) {
  Integer retVal;
  try {
    retVal = Integer.parseInt(str);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}
Simulant
  • 19,190
  • 8
  • 63
  • 98
3

It is not a good idea to use exceptions to control flow - they should only be used as exceptions.

This is a classic problem with a regex solution:

class ValidNumber {

    // Various simple regexes.
    // Signed decimal.
    public static final String Numeric = "-?\\d*(.\\d+)?";
    // Signed integer.
    public static final String Integer = "-?\\d*";
    // Unsigned integer.
    public static final String PositiveInteger = "\\d*";

    // The valid pattern.
    final Pattern valid;

    public ValidNumber(String validRegex) {
        this.valid = Pattern.compile(validRegex);
    }

    public boolean isValid(String str) {
        return valid.matcher(str).matches();
    }

}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213