Java 如何检查字符串是否可解析为双精度值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3543729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check that a string is parseable to a double?
提问by Louis Rhys
Is there a native way (preferably without implementing your own method) to check that a string is parseable with Double.parseDouble()
?
是否有一种本机方式(最好不实现您自己的方法)来检查字符串是否可解析Double.parseDouble()
?
采纳答案by Johannes Wachter
The common approach would be to check it with a regular expression like it's also suggested inside the Double.valueOf(String)
documentation.
常见的方法是使用正则表达式检查它,就像Double.valueOf(String)
文档中也建议的那样。
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.
如果您不想这样做,try catch
仍然是一种选择。
The regexp suggested by the JavaDoc is included below:
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
}
回答by jdc0589
You can always wrap Double.parseDouble() in a try catch block.
您始终可以将 Double.parseDouble() 包装在 try catch 块中。
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
回答by CoolBeans
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
回答by bluedevil2k
Apache
, as usual, has a good answer from Apache Commons-Lang
in the form of
NumberUtils.isCreatable(String)
.
Apache
,像往常一样,有一个很好的答案 fromApache Commons-Lang
的形式
NumberUtils.isCreatable(String)
。
Handles null
s, no try
/catch
block required.
句柄null
s,不需要try
/catch
块。
回答by Zach-M
All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:
所有答案都可以,这取决于您想成为的学术水平。如果您希望准确地遵循 Java 规范,请使用以下内容:
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.
此代码基于Double处的 JavaDocs 。
回答by ruhong
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.
谷歌的番石榴库提供了一个很好的辅助方法来做到这一点:Doubles.tryParse(String)
。您可以像这样使用它,Double.parseDouble
但null
如果字符串未解析为双精度值,它会返回而不是抛出异常。