Java library to check whether a String contains a number *without* exceptions

前端 未结 5 494
长情又很酷
长情又很酷 2020-12-18 00:50

I\'m looking for a method that returns a boolean if the String it is passed is a valid number (e.g. \"123.55e-9\", \"-333,556\"). I don\'t want to just do:

5条回答
  •  半阙折子戏
    2020-12-18 01:15

    I would avoid re-inventing this method and go with Apache Commons. If your using Spring, Struts or many other commonly used java libraries, they often have Apache commons included. You will want the commons-lang.jar file. Here is the method in NumberUtils you would want:

    isNumber[1]
    
    public static boolean isNumber(java.lang.String str)
    Checks whether the String a valid Java number.
    
    Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
    
    Null and empty String will return false.
    
    Parameters:
    str - the String to check
    Returns:
    true if the string is a correctly formatted number
    

提交回复
热议问题