Sunday, 1 May 2016

How to check if a String is numeric in Java



How would you check if a String was a number before parsing it?


Answer



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



With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.




You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...