-1

So I want to check whether my String can be number or not. I don't want write any boiler plate code for that. There's one method of common-apache isNumeric()
But it gives true for "" blank value and false for decimal values (12.3)
So is there any other method which might do it all ?

  • duplicate of [https://stackoverflow.com/questions/1102891/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) – DTul Jan 25 '19 at 09:37
  • What is `common-apache`? And what exactly do you accept as valid "number" string? – ernest_k Jan 25 '19 at 09:38

5 Answers5

1

Easiest way is to parse it via a method.

exp.

try {
        double d = Double.parseDouble(STRING_TO_TEST);
    } catch (NumberFormatException | NullPointerException e) {
        //do logic 
    }
    return true;

But if you dont need this, Apache Commons has a useful method: exp.

NumberUtils.isCreatable("22.6") ;

which returns true

NumberUtils.isCreatable("") ;

which returns false

More info : https://www.baeldung.com/java-check-string-number

Bon
  • 250
  • 3
  • 10
1
public boolean isNumber(String s) {
  try {
    Double.parseDouble(yourString);
    return true;
  } catch(Exception e) {
    return false;
  } 
}

This will give you true if Java can resolve it

mmarek
  • 11
  • 1
0

You can use regex for this. The regex would be : [0-9]+

Here are some examples:

String regex = "[0-9]+";
System.out.println("12".matches(regex));
System.out.println("abc".matches(regex));
System.out.println("".matches(regex));

If you want to consider the decimal values as well, then you can use [0-9]+(\.)?[0-9]* as regex.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

Yes, in apache commons library there exists the NumberUtils class (org.apache.commons.lang3.math.NumberUtils) having the below given method.

 public static boolean isParsable(String str)

This checks whether the given String is a parsable number. Please find the detailed documentation here https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

ajith george
  • 538
  • 1
  • 5
  • 14
0

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/math/NumberUtils.html#isCreatable-java.lang.String-