0

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

xingbin
  • 27,410
  • 9
  • 53
  • 103
  • 1
    You want only single digits? – NiVeR Jun 24 '18 at 16:37
  • Possible duplicate of [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java) – Saurabh Bhoomkar Jun 24 '18 at 16:38
  • You can start by removing the first half of the method, since you don't do anything with the boolean value that it computes. – JB Nizet Jun 24 '18 at 16:38
  • I would suggest to use a lib if you dont have to write yourself: https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java – hasan Jun 24 '18 at 16:40
  • If you're using Guava, `return Doubles.tryParse(s) != null;` – shmosel Jun 24 '18 at 17:30

5 Answers5

2

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;
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
0

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;
  }
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18
0

you can simply do this:

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

if "." is the separator for decimals

GJCode
  • 1,959
  • 3
  • 13
  • 30
0

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 }
}
ci0ccarellia
  • 795
  • 9
  • 26
0

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