Is there a native way (preferably without implementing your own method) to check that a string is parsable with Double.parseDouble()
?
views:
162answers:
4
+4
A:
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
jdc0589
2010-08-22 22:36:39
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
2010-08-23 02:17:12
+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
2010-08-22 22:37:19
@Louis Rhys - There is a code example in the documentation link in the answer.
Starkey
2010-08-22 22:44:22
@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
2010-08-22 22:45:49
+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
2010-08-22 22:43:50
actually it's more complicated than that. see johannes wachter's answer
Louis Rhys
2010-08-22 22:47:29
+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
2010-08-22 23:53:46
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
2010-08-23 02:14:58