Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant isNumeric() solution for java

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?

like image 245
Doug Avatar asked Aug 17 '10 21:08

Doug


4 Answers

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.

like image 130
Jacob Mattison Avatar answered Oct 15 '22 11:10

Jacob Mattison


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)

like image 22
Fanny H. Avatar answered Oct 15 '22 10:10

Fanny H.


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.

like image 33
Colin Hebert Avatar answered Oct 15 '22 10:10

Colin Hebert


Optionally you can use a regular expression as well.

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

    return false;
like image 31
vicsz Avatar answered Oct 15 '22 10:10

vicsz