Most elegant isNumeric() solution for java

前端 未结 7 896
囚心锁ツ
囚心锁ツ 2021-02-13 01:31

I\'m porting a small snippet of PHP code to java right now, and I was relying on the function is_numeric($x) to determine if $x is a number or not. Th

相关标签:
7条回答
  • 2021-02-13 01:57

    Have you looked into using StringUtils library? There's a isNumeric() function which might be what you're looking for. (Note that "" would be evaluated to true)

    0 讨论(0)
  • 2021-02-13 02:05

    Just use if((x instanceof Number)

    //if checking for parsable number also

    || (x instanceof String && x.matches("((-|\+)?[0-9]+(\.[0-9]+)?)+"))

    ){ ... }
    //---All numeric types including BigDecimal extend Number

    0 讨论(0)
  • 2021-02-13 02:06

    Optionally you can use a regular expression as well.

       if (theString.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")))
         return true;
    
        return false;
    
    0 讨论(0)
  • 2021-02-13 02:07

    In a strongly typed language, a generic isNumeric(String num) method is not very useful. 13214384348934918434441 is numeric, but won't fit in most types. Many of those where is does fit won't return the same value.

    As Colin has noted, carrying numbers in Strings withing the application is not recommended. The isNumberic function should only be applicable for input data on interface methods. These should have a more precise definition than isNumeric. Others have provided various solutions. Regular expressions can be used to test a number of conditions at once, including String length.

    0 讨论(0)
  • 2021-02-13 02:14

    Did you try Integer.parseInt()? (I'm not sure of the method name, but the Integer class has a method that creates an Integer object from strings). Or if you need to handle non-integer numbers, similar methods are available for Double objects as well. If these fail, an exception is thrown.

    If you need to parse very large numbers (larger than int/double), and don't need the exact value, then a simple regex based method might be sufficient.

    0 讨论(0)
  • 2021-02-13 02:17

    It's usually a bad idea to have a number in a String. If you want to use this number then parse it and use it as a numeric. You shouldn't need to "check" if it's a numeric, either you want to use it as a numeric or not.

    If you need to convert it, then you can use every parser from Integer.parseInt(String) to BigDecimal(String)

    If you just need to check that the content can be seen as a numeric then you can get away with regular expressions.

    And don't use the parseInt if your string can contain a float.

    0 讨论(0)
提交回复
热议问题