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.

1
  • why don't you try this approach??? Commented May 27, 2014 at 11:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

}

1 Comment

Apache Commons has done the work for you already. See NumberUtils.isDigits (fuller answer given below).
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.