user9623263
user9623263

Reputation:

Java method which check is it a number

I have wrote a method which takes a string and return true if its a valid single integer or floating number or false if its not.

My code:

public static boolean isDigit(String s)
    {
        boolean b;
        try
        {
            Integer.parseInt(s);
            b = true;
        }
        catch (NumberFormatException e)
        {
            b = false;
        }

        try
        {
            Double.parseDouble(s);
            b = true;
        }
        catch (NumberFormatException e)
        {
            b = false;
        }

        return b;
    }

I am sure there is a better way of writing it. Thank you

Upvotes: 0

Views: 849

Answers (5)

CodeRonin
CodeRonin

Reputation: 2109

you can simply do this:

 return s.matches("[+-]?\\d+(\\.\\d+)?");

if "." is the separator for decimals

Upvotes: 0

iqval singh
iqval singh

Reputation: 16

Use Apache Commons StringUtils.isNumeric() to check if String is valid number

Examples:-

StringUtils.isNumeric("123") = true StringUtils.isNumeric(null) = false StringUtils.isNumeric("") = false StringUtils.isNumeric(" ") = false

Upvotes: 0

Torcione
Torcione

Reputation: 845

The lightest solution is this one, also for code readability:

public boolean isDigit(String str) {
     try {
          Integer.parseInt(str)
          return true;
     } catch (NumberFormatException: e) { return false }
}

Upvotes: 0

Gaurav Srivastav
Gaurav Srivastav

Reputation: 2561

You do this using Regular expression too.

 public static boolean isDigit(String s){
    String regex = "[0-9]*\\.?[0-9]*";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(s);
    boolean b = m.matches();
    return b;
  }

Upvotes: 0

xingbin
xingbin

Reputation: 28289

You do not need check if it is int, since int number can also be parsed to double. It can be simplified to this:

public static boolean isDigit(String s)
{
    boolean b;

    try
    {
        Double.parseDouble(s);
        b = true;
    }
    catch (NumberFormatException e)
    {
        b = false;
    }

    return b;
}

Upvotes: 2

Related Questions