How to check that a string is parseable to a double?

JavaStringParsingFloating Point

Java Problem Overview


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

Java Solutions


Solution 1 - Java

Apache, as usual, has a good answer from Apache Commons-Lang in the form of NumberUtils.isCreatable(String).

Handles nulls, no try/catch block required.

Solution 2 - Java

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

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

Solution 3 - Java

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

The regexp provided there (or included below) 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.

The regexp suggested by the JavaDoc is included below:

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
}

Solution 4 - Java

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  

Solution 5 - Java

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.

Solution 6 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLouis RhysView Question on Stackoverflow
Solution 1 - Javabluedevil2kView Answer on Stackoverflow
Solution 2 - Javajdc0589View Answer on Stackoverflow
Solution 3 - JavaJohannes WachterView Answer on Stackoverflow
Solution 4 - JavaCoolBeansView Answer on Stackoverflow
Solution 5 - JavaruhongView Answer on Stackoverflow
Solution 6 - JavaZach-MView Answer on Stackoverflow