javastringnumeric

How to check if a String is numeric in Java


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


Solution

  • 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.)