Is there a better, more elegant (and/or possibly faster) way than
boolean isNumber = false; try{ Double.valueOf(myNumber); isNumber = true; } catch (NumberFormatException e) { }
…?
Edit: Since I can’t pick two answers I’m going with the regex one because a) it’s elegant and b) saying ‘Jon Skeet solved the problem’ is a tautology because Jon Skeet himself is the solution to all problems.
I don’t believe there’s anything built into Java to do it faster and still reliably, assuming that later on you’ll want to actually parse it with Double.valueOf (or similar).
I’d use Double.parseDouble instead of Double.valueOf to avoid creating a Double unnecessarily, and you can also get rid of blatantly silly numbers quicker than the exception will by checking for digits, e/E, – and . beforehand. So, something like:
Note that despite taking a couple of tries, this still doesn’t cover ‘NaN’ or hex values. Whether you want those to pass or not depends on context.
In my experience regular expressions are slower than the hard-coded check above.