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 ?

- 7
- 4
-
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 Answers
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

- 250
- 3
- 10
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

- 11
- 1
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.

- 30,102
- 11
- 68
- 102
-
-
@JoakimDanielson updated the answer just before this comment was posted. – Darshan Mehta Jan 25 '19 at 09:40
-
-
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-

- 538
- 1
- 5
- 14
With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

- 1
- 3