views:

162

answers:

4

Is there a native way (preferably without implementing your own method) to check that a string is parsable with Double.parseDouble()?

+4  A: 

You can always wrap Double.parseDouble() in a try catch block.

try
{
  Double.parseDouble(number);
}
catch(NumberFormatException e)
{
  //not a double
}
jdc0589
This would be my preferred method because your guaranteed to get exactly the same behavior as the parse. It's very easy with a custom regular expression to overlook edge cases.
Chris Nava
+10  A: 

The common approach would be to check it with a regular expression like it's also suggested inside the Double documentation.

The regexp provided there should cover all valid floating point cases, so you don't need to fiddle with it, since you will eventually miss out on some of the finer points.

If you don't want to do that, try catch is still an option.

Johannes Wachter
+1 - Much better than catching an exception (my lame answer...)
Starkey
how does one do this exactly?
Louis Rhys
@Louis Rhys - There is a code example in the documentation link in the answer.
Starkey
@Louis Rhys: The complete code you need is provided in behind the link. You just need to copy that into your code and wrap the final if statement around your use of `Double.parseDouble`. But I would put the could into a utility class or method so it's easier reusable in your project. Something like `parseDoubleSafe(String check, Double default)` or something like that.
Johannes Wachter
oh ok found that. Thanks!
Louis Rhys
+1  A: 

Something like below should suffice :-

String decimalPattern = "([0-9]*)\\.([0-9]*)";  
String number="20.00";  
boolean match = Pattern.matches(decimalPattern, number);
System.out.println(match); //if true then decimal else not  
CoolBeans
actually it's more complicated than that. see johannes wachter's answer
Louis Rhys
Got it. The link that Wachter provided is helpful indeed.
CoolBeans
+4  A: 

Apache, as usual, has a good answer

NumberUtils.isNumber(string);

Handles nulls, no try/catch block. That's in the Lang package I believe.

bluedevil2k
does Apache ship with the normal JDK?
Louis Rhys
No. You can find the Apache Commons libraries here. http://commons.apache.org/ Highly recommended that you use them rather than writing custom code whenever you can.
Chris Nava