簡體   English   中英

如何檢查字符串是否為正數、負數或不是數字

[英]How to check if a string is a positive number, negative number or not a number

問題

我有一個String ,我想知道該String是否是一個數字,它也可能是一個負數

測試用例

String test1  = "abcd";     // Here it must show that it's not a number
String test2  = "abcd-123"; // Here it must show that it's not a number
String test3  = "123";      // Here it must show that it's a number
String test4  = "-.12";     // Here it must show that it's a number
String test5  = "-123";     // Here it must show that it's a number
String test6  = "123.0;     // Here it must show that it's a number
String test7  = "-123.00";  // Here it must show that it's a number
String test8  = "-123.15";  // Here it must show that it's a number
String test9  = "09";       // Here it must show that it's a number
String test10 = "0.0";      // Here it must show that it's a number

試過的東西

我使用了StringUtils#isNumberNumberUtils#isNumber ,但它們沒有幫助,負數,“09”顯示為不是數字

你可以試試這個:

try {
    double value = Double.parseDouble(test1);
    if(value<0)
       System.out.println(value + " is negative");
    else
       System.out.println(value + " is possitive");
} catch (NumberFormatException e) {
    System.out.println("String "+ test1 + "is not a number");
}

根據Double.valueOf的 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
  }

正則表達式內容豐富,但內容全面且有據可查。 你可以隨意修剪它。

嘗試使用 catch 語句將輸入解析為圍繞它的整數,如果它不轉換它應該返回 input 是一個字符如果它轉換它返回 input 是一個數字

 public static String checknumeric(String str){
        String numericString = null;
        String temp;
      if(str.startsWith("-")){ //checks for negative values
          temp=str.substring(1);
          if(temp.matches("[+]?\\d*(\\.\\d+)?")){
              numericString=str;
          }
      }
        if(str.matches("[+]?\\d*(\\.\\d+)?")) {
            numericString=str;
        }
        return numericString;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM