Is there a native way (preferably without implementing your own method) to check that a string is parseable with Double.parseDouble()
?
This question is related to
java
string
parsing
floating-point
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:
private static final Pattern DOUBLE_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
public static boolean isFloat(String s)
{
return DOUBLE_PATTERN.matcher(s).matches();
}
This code is based on the JavaDocs at Double.
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
Google's Guava library provides a nice helper method to do this: Doubles.tryParse(String)
. You use it like Double.parseDouble
but it returns null
rather than throwing an exception if the string does not parse to a double.
Apache
, as usual, has a good answer from Apache Commons-Lang
in the form of
NumberUtils.isCreatable(String)
.
Handles null
s, no try
/catch
block required.
Source: Stackoverflow.com