检查字符串值是否等于double?

时间:2014-01-07 00:17:38

标签: java variables performance

我有多个字符串可能等于或不等于double值(例如“444”,“44.4”,“ - 0.0044”)。我想知道最有效的方法是检查它是否等于双倍。起初我使用的是try-catch语句,但StackOverflow上的其他帖子表示,如果抛出异常,那些性能代价很高。这是我到目前为止的代码:

try { 
     double a = Double.parseDouble("444");
     return true;
}
catch (NumberFormatException e) {
     return false;
}

3 个答案:

答案 0 :(得分:3)

Java指定一个正则表达式,可用于验证在Double.valueOf的Javadoc中传递给Double.parseDoubleDouble.valueOf的字符串:

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 section 3.10.2 of
   // The Java™ Language Specification.

   // 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
 }

答案 1 :(得分:1)

如果(正如标题所示)您正在测试String等于特定 double,那么最简单快捷的方法是将double转换为String然后比较:

if (Double.toString(d).equals(s))

而不是处理解析字符串的变幻莫测和异常。


如果您的代码建议,您正在测试String是否可以解析(作为任何 double),您拥有的代码现在可能是最好的方式。解析浮点数非常复杂,必须在某处完成工作 - 也许让API完成工作。此外,抛出异常 非常昂贵。

如果您当前的工作实施被证明太慢而无法容忍,则只寻求优化性能。除非你每秒解析数百个,否则我不会担心。

答案 2 :(得分:0)

此问题的过去答案表示使用API​​ docs中的模式

使用预编译的RegEx
Pattern redbl=Pattern.compile("[\\x00-\\x20]*[+-]?(((((\\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]*");
Boolean isDouble=redbl.matcher("444.123").matches();
相关问题