Most elegant isNumeric() solution for java

2019-03-24 05:49发布

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. There doesn't seem to be an equivalent function in java, and I'm not satisfied with the current solutions I've found so far.

I'm leaning toward the regular expression solution found here: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric

Which method should I use and why?

7条回答
叛逆
2楼-- · 2019-03-24 06:25

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.

查看更多
看我几分像从前
3楼-- · 2019-03-24 06:31

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

查看更多
虎瘦雄心在
4楼-- · 2019-03-24 06:32

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)

查看更多
Root(大扎)
5楼-- · 2019-03-24 06:33

Note that the PHP isNumeric() function will correctly determine that hex and scientific notation are numbers, which the regex approach you link to will not.

One option, especially if you are already using Apache Commons libraries, is to use NumberUtils.isNumber(), from Commons-Lang. It will handle the same cases that the PHP function will handle.

查看更多
做个烂人
6楼-- · 2019-03-24 06:33

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.

查看更多
叛逆
7楼-- · 2019-03-24 06:39

Optionally you can use a regular expression as well.

   if (theString.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")))
     return true;

    return false;
查看更多
登录 后发表回答