How to check that a string is parseable to a double?
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
}
How to check if the value of string variable is double
Yes, they are valid values for double
: See the documentation.
Just update your method to include the checks on NaN
and Infinity
:
public static bool IsDoubleRealNumber(string valueToTest)
{
if (double.TryParse(valueToTest, out double d) && !Double.IsNaN(d) && !Double.IsInfinity(d))
{
return true;
}
return false;
}
How to check if a String is a valid int or double
You could write a function to test it by calling Double.parseDouble(String)
and catching the NumberFormatException
(this will handle double
and int
values) when it isn't like
public static boolean isNumber(String str) {
try {
double v = Double.parseDouble(str);
return true;
} catch (NumberFormatException nfe) {
}
return false;
}
Then you could call it like
if (isNumber(tokens[2])) {
System.out.println(" Invalid make");
}
And the printf
with String
might look like,
String msg = "Invalid make";
System.out.printf(" %s%n", msg);
How to determine if a string is of type Double or Long
Why don't you try Long.valueOf(String)
to first parse it as a Long
, and failing that parse it as a Double
with Double.valueOf(String)
?
Both throw a NumberFormatException
if the string cannot be parsed.
public static void main(String[] args) throws Exception {
final String s1 = "1234567890";
System.out.println(isParsableAsLong(s1)); // true
System.out.println(isParsableAsDouble(s1)); // true
final String s2 = "1234.56789";
System.out.println(isParsableAsLong(s2)); // false
System.out.println(isParsableAsDouble(s2)); // true
}
private static boolean isParsableAsLong(final String s) {
try {
Long.valueOf(s);
return true;
} catch (NumberFormatException numberFormatException) {
return false;
}
}
private static boolean isParsableAsDouble(final String s) {
try {
Double.valueOf(s);
return true;
} catch (NumberFormatException numberFormatException) {
return false;
}
}
Related Topics
Reading and Displaying Data from a .Txt File
Best Language to Parse Extremely Large Excel 2007 Files
Generating All Possible Permutations of a List Recursively
Right Way to Write JSON Deserializer in Spring or Extend It
How to Find Out If "Debug Mode" Is Enabled
How to Get Subnet Mask of Local System Using Java
Changing Shape of Single Point in Jfreechart Xyplot
Reverse Java Graphics2D Scaled and Rotated Coordinates
Circular Dependency in Java Constructors
Building an Uberjar with Gradle
Creating New Generic Object with Wildcard
Jce Cannot Authenticate the Provider Bc in Java Swing Application
A Confusion About Java String Literal Pool and String's Concatenation
Gc Overhead of Optional<T> in Java
Absolute Minimum Code to Get a Valid Oauth_Signature Populated in Java or Groovy
Parsing PDF Files (Especially with Tables) with PDFbox
Converting String to Date Using Simpledateformat Is Returning Random Date