How to check if a String is numeric in Java

前端 未结 30 2600
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

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

30条回答
  •  梦毁少年i
    2020-11-21 05:57

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

提交回复
热议问题