На этот вопрос уже есть ответ:
Есть ли собственный способ (предпочтительно без реализации собственного метода), чтобы проверить, что строка разбирается с Double.parseDouble ()
?
Общим подходом будет проверка с помощью регулярного выражения, как это также предлагается в Double.valueOf(String)
документации.
Регулярное выражение, приведенное там (или включенное ниже), должно охватывать все допустимые случаи с плавающей точкой, так что вам не нужно возиться с ним, поскольку вы в конечном итоге упустите некоторые тонкие моменты.
Если вы не хотите этого делать, try catch
все еще является вариантом.
Regexp, предложенный в JavaDoc, приведен ниже:
final String Digits = "(\\p{Digit}+)";
final String HexDigits = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
final String Exp = "[eE][+-]?"+Digits;
final String fpRegex =
("[\\x00-\\x20]*"+ // Optional leading "whitespace"
"[+-]?(" + // Optional sign character
"NaN|" + // "NaN" string
"Infinity|" + // "Infinity" string
// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
//
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from the Java Language Specification, 2nd
// edition, section 3.10.2.
// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
// . Digits ExponentPart_opt FloatTypeSuffix_opt
"(\\.("+Digits+")("+Exp+")?)|"+
// Hexadecimal strings
"((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "(\\.)?)|" +
// 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
")[pP][+-]?" + Digits + "))" +
"[fFdD]?))" +
"[\\x00-\\x20]*");// Optional trailing "whitespace"
if (Pattern.matches(fpRegex, myString)){
Double.valueOf(myString); // Will not throw NumberFormatException
} else {
// Perform suitable alternative action
}
Apache
, как обычно, имеет хороший ответ от Apache Commons-Lang
в виде
NumberUtils.isCreatable (строка)
.
Обрабатывает null
s, не требуется блок try
/ catch
.
Что-то вроде следующего должно быть достаточно :-
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
Вы всегда можете обернуть Double.parseDouble() в блок try catch.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}