简体   繁体   中英

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

Problem

I have a String and I want to know if the String is a number, it could be also a negative number

Test cases

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

Tried stuff

I used StringUtils#isNumber and NumberUtils#isNumber , but they don't help, negative numbers , "09" show as not a number

You can try this:

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");
}

According to the Javadoc of Double.valueOf :

To avoid calling this method on an invalid string and having a NumberFormatException be thrown, the regular expression below can be used to screen the input string:

  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
  }

The regular expression is substantial, but comprehensive and well-documented. You can trim it as you like.

尝试使用 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM