Most elegant isNumeric() solution for java

Viewed 39646

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 Answers

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

Related