栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java 如何检查字符串可解析为双精度?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 如何检查字符串可解析为双精度?

常见方法是使用正则表达式进行检查,就像

Double.valueOf(String)
文档中也建议的那样。

此处提供的regexp(或下面包含的)应涵盖所有有效的浮点数情况,因此你无需费心处理,因为你最终会错过一些更好的点。

如果你不想这样做,

try catch
仍然可以选择。

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}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/447043.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号