I know there's a million ways of doing this but what is the fastest? This should include scientific notation.
NOTE: I'm not interested in converting the value to Double, i'm only interested in knowing if it's possible. i.e. private boolean isDouble(String value)
.
Exceptions shouldn't be used for flow control, though Java's authors made it difficult to not use
NumberFormatException
that way.The class
java.util.Scanner
has a methodhasNextDouble
to check whether aString
can be read as a double.Under the hood
Scanner
uses regular expressions (via pre-compiled patterns) to determine if aString
can be converted to a integer or floating point number. The patterns are compiled in the methodbuildFloatAndDecimalPattern
which you can view at GrepCode here.A pre-compiled pattern has the added benefit of being faster than using a try/catch block.
Here's the method referenced above, in case GrepCode disappears one day:
There is a handy
NumberUtils#isNumber
in Apache Commons Lang. It is a bit far fetched:but I guess it might be faster than regular expressions or throwing and catching an exception.
You can check it using the same regular expression the Double class uses. It's well documented here:
http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf%28java.lang.String%29
Here is the code part:
I have tried below code block and seems like throwing exception more faster
Output:
I use the following code to check if a string can be parsed to double:
I am aware that the output is not exactly the same as for the regular expression in the Double class but this method is much faster and the result is good enough for my needs. These are my unit tests for the method.
The Apache Commons NumberUtil is actually quite fast. I'm guessing it's way faster than any regexp implementation.