Comment vérifier qu’une chaîne est analysable en double?

Existe-t-il une méthode native (de préférence sans implémenter votre propre méthode) pour vérifier qu’une chaîne est Double.parseDouble() avec Double.parseDouble() ?

L’approche commune serait de le vérifier avec une expression régulière comme cela est également suggéré dans la documentation Double.valueOf(Ssortingng) .

L’expression rationnelle fournie ici (ou incluse ci-dessous) devrait couvrir toutes les observations en virgule flottante, vous n’avez donc pas besoin de la manipuler car vous finirez par manquer certains des points les plus fins.

Si vous ne voulez pas le faire, try catch est toujours une option.

L’expression rationnelle suggérée par JavaDoc est incluse ci-dessous:

 final Ssortingng Digits = "(\\p{Digit}+)"; final Ssortingng HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. final Ssortingng Exp = "[eE][+-]?"+Digits; final Ssortingng fpRegex = ("[\\x00-\\x20]*"+ // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" ssortingng "Infinity|" + // "Infinity" ssortingng // A decimal floating-point ssortingng 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 ssortingngs as input // in addition to ssortingngs 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 ssortingngs "((" + // 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, mySsortingng)){ Double.valueOf(mySsortingng); // Will not throw NumberFormatException } else { // Perform suitable alternative action } 

Apache, comme d’habitude, a une bonne réponse d’ Apache Commons-Lang sous la forme de org.apache.commons.lang3.math.NumberUtils.isNumber(Ssortingng)

Gère les valeurs NULL, pas de bloc try / catch requirejs.

Vous pouvez toujours envelopper Double.parseDouble () dans un bloc try catch.

 try { Double.parseDouble(number); } catch(NumberFormatException e) { //not a double } 

Quelque chose comme ci-dessous devrait suffire: –

 Ssortingng decimalPattern = "([0-9]*)\\.([0-9]*)"; Ssortingng number="20.00"; boolean match = Pattern.matches(decimalPattern, number); System.out.println(match); //if true then decimal else not 

La bibliothèque Guava de Google fournit une méthode d’aide très Doubles.tryParse(Ssortingng) pour ce faire: Doubles.tryParse(Ssortingng) . Vous l’utilisez comme Double.parseDouble mais il retourne null plutôt que de lancer une exception si la chaîne n’parsing pas un double.

Toutes les réponses sont correctes, en fonction de votre niveau académique. Si vous souhaitez suivre les spécifications Java avec précision, utilisez ce qui suit:

 private static final Pattern DOUBLE_PATTERN = Pattern.comstack( "[\\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(Ssortingng s) { return DOUBLE_PATTERN.matcher(s).matches(); } 

Ce code est basé sur les JavaDocs à Double .