我得到一个double
类型的值,因此该值将是数字,并且可以包含十进制,如下所示
Double d = Double.parseDouble((cell.getStringCellValue()))
brokerInvoiceLineItem.setFixedRate(d);
因此,如上所示,我们从 excel 工作表中读取一个字符串类型的值,然后将其解析为双精度类型,因此最终此双精度类型的值可以是
1.38
1.0725
2,175000
现在我想实现一个检查,即双精度类型 D 变量的值应该只是数字,它可以包含由小数位分隔的浮点值,但它不应该包括字母数字字符串,该值不应该是类型
+13.5 BPTS
所以请告知IU如何把这个检查放在自己之前
伙计们请告诉我如何检查双精度类型值不应该有任何字符串,是否有任何正则表达式来检查它
确保字符串可以使用Double.parseDouble(String s)
解析为double
,请参阅Double.valueOf(String s)
的javadoc中提供的正则表达式:
为了避免对无效字符串调用此方法并引发
NumberFormatException
,可以使用下面的正则表达式来筛选输入字符串: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 }
我认为有更简单的方法。如果您已经在使用Double.parseDouble()
那么您的工作几乎已经完成。 parseDouble()
方法抛出一个NumberFormatException
,如果字符串输入不包含可解析的双精度
因此,您可以将代码包装在try
块中,catch
NumberFormatException
并在那里处理它。
代码应该看起来像
try{
Double d = Double.parseDouble((cell.getStringCellValue()))
brokerInvoiceLineItem.setFixedRate(d);
}
catch(NumberFormatException e){
System.out.println("Input was not parsable");
}