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

标签 java variables performance

<分区>

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

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

最佳答案

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
 }

关于java - 检查字符串值是否等于 double 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20961762/

相关文章:

java - 与经济数据的比较逻辑错误 - 比较方法违反了其一般契约

java - JUNG,在可视化查看器上更改图形引用

php - 为什么我不能索引 mysql 返回的数组?

PHP MYSQL 日期格式输出为零

c# - (DbContext) SaveChanges() 如何用于大量记录? - 寻求和找到最佳性能的解决方案

java - 将现有的 SQLite 数据库加载到内存

java - 安卓/Java |抽屉导航的 TextView .setText 无法通过 SharedPreferences 工作

java - Hibernate查询多个关联

javascript - 将全局变量传递给函数 - 函数运行后全局变量不更新

c - 骑士游算法C实现性能